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.
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.