This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I have a requirement wherein I need to download a file from a server. But this download should take max x secs. If it exceeds this time, I should abort and move forward. What is the best way to achieve this? I was thinking on the lines of timed wait but in that, I would need to kill the download thread on timeout. Any other options?
How are you establishing a connection to the server and how drastically do you want to enforce the time-out?
For instance, if you're establishing a connection using a plain old Socket you can use setSoTimeout() method to tell the Socket to block for a specified period of time.
If no data can be read within that time period an exception will be raised. If you establish a connection using a URLConnection its setReadTimeout() method allows you to do something similar.
However, that's not a viable solution if you want to break-off a download in-progress after a specified time-out where data is actually successfully being read, but the download just hasn't completed yet due to a slow connection.
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Joined: Jan 01, 2007
I am establishing the connection using urlconnection and am using setReadTimeout. In addition, I want to abort ongoing download as well if it timesout.
You could use a ScheduledExecutorService to schedule a Runnable that opens the URLConnection and starts the download using a URLconnection.
The ScheduledExecutorService creates and returns a ScheduledFuture that you can use as a handle to cancel execution after a specified delay.
The ScheduledFuture also provides method to retrieve the result when the task has completed and it also provides methods to check whether the task has completed normally or if it was cancelled.
Upon cancellation (and completion) you can simply close the InputStream associated with the URLConnection.