lunes, junio 10, 2013

Implementing Timeouts with FutureTask



Sometimes when you are writing some code that needs communication with external systems, not necessarily by using a socket, for example it can be using a serial port, we may need a way to implement a timeout algorithm, so if after some specified time, the request does not return a result, a timeout error should be thrown so user can act in consequence, and not wait indefinitely for a result that maybe will never come.

If the API being used contains a read method with timeout, then the problem is easily fixed by catching the exception, but if not, then you must implement yourself the timeout logic. To do that we can use FutureTask class.


Basically what we are doing is creating a FutureTask object, and creating a Callable interface which executes the call method which requires a timeout. Then we create a thread to execute it. And finally we call get method, which waits until the result is calculated, or if the timeout exceeds (in this case 5 seconds), TimeoutException is thrown.

So we have seen a really easy way to implement a timeout feature for our application.

We keep learning,
Alex
When the garden flowers baby are dead yes, And your mind [, your mind] is [so] full of RED, Don't you want somebody to love, Don't you need somebody to love (Somebody to love - Jefferson Airplane)