This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes Timeout a thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Timeout a thread" Watch "Timeout a thread" New topic
Author

Timeout a thread

Satya Maheshwari
Ranch Hand

Joined: Jan 01, 2007
Posts: 368
Hi

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?

Thanks and Regards
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1763
    
    7

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.
Satya Maheshwari
Ranch Hand

Joined: Jan 01, 2007
Posts: 368
Thanks Jelle!
I am establishing the connection using urlconnection and am using setReadTimeout. In addition, I want to abort ongoing download as well if it timesout.
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1763
    
    7

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.
Satya Maheshwari
Ranch Hand

Joined: Jan 01, 2007
Posts: 368
Great! Thanks Jelle!
 
GeeCON Prague 2014
 
subject: Timeout a thread