File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Timeout a thread

 
Satya Maheshwari
Ranch Hand
Posts: 368
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Jelle Klap
Bartender
Posts: 1951
7
Eclipse IDE Java
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Satya Maheshwari
Ranch Hand
Posts: 368
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1951
7
Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 368
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great! Thanks Jelle!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic