Last Updated: February 25, 2016
· lordofthejars

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.

FutureTask<MyResult> timeoutTask = null;
try {
timeoutTask = new FutureTask<MyResult>(new Callable<MyResult>() {

        public MyResult call() throws Exception {
            MyResult result = //expensive operation
            return result;

new Thread(timeoutTask).start();
MyResult result = timeoutTask.get(5L, TimeUnit.SECONDS);
} catch (InterruptedException e) {

} catch (ExecutionException e) {

} catch (TimeoutException e) {


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 returns the result, 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.

Say Thanks

2 Responses
Add your response


Good tip
Why don't you use an Executor implementation ?


over 1 year ago ·

yes you can do it calling ExecutorService.submit method.

over 1 year ago ·