aspose file tools*
The moose likes Threads and Synchronization and the fly likes Help in FutureTask class with function timeout Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Help in FutureTask class with function timeout " Watch "Help in FutureTask class with function timeout " New topic
Author

Help in FutureTask class with function timeout

Ajay Singh
Ranch Hand

Joined: Jan 04, 2008
Posts: 105
Hi
I want to test the timeout functionality of java using futuretask and callable interface. Here is my code. Basically i have three sentences in my array.I want to time out(5 seconds) the second sentence based on the futuretask.get(long,timeunit) method as shown in the code below.for the second sentence i am just calling an infinite loop in the "blockingFunction" function.I am able to catch the timeout exception for the second sentence but i see that the loop continues running evern after the time out exception.Please tell me where i am going wrong.
Ranganathan Kaliyur Mannar
Bartender

Joined: Oct 16, 2003
Posts: 1089
    
  10

first of all, the get(timeout) doesn't end the task. The javadoc for get says:
Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

so, in your case, as the task is still running, it threw a TimeOutException... i.e your task did not end in 5 seconds - because you are calling an infinite loop, it will never end...

In the exception block, I see that you call futureTask.cancel(true)...even this would not end the task. This is because, cancel attempts to interrupt the task. As you have not handled interrupts in your loop, this would also not end the task.

Correct way to write your task will be to:

But, note that, this will still not stop the task when get() is called. Will end only when cancel(true) is called.


Ranga.
SCJP 1.4, OCMJEA/SCEA 5.0.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help in FutureTask class with function timeout