Executor Service - timeout of thread Executor Service - timeout of thread multithreading multithreading

Executor Service - timeout of thread


my callable will interrupt after the specified time(timeout) has passed

Not true. The task will continue to execute, instead you will have a null string after the timeout.

If you want to cancel it:

  timeout.cancel(true) //Timeout timeout = new Timeout();

P.S. As you have it right now this interrupt will have no effect what so ever. You are not checking it in any way.

For example this code takes into account interrupts:

    private static final class MyCallable implements Callable<String>{    @Override    public String call() throws Exception {        StringBuilder builder = new StringBuilder();        try{            for(int i=0;i<Integer.MAX_VALUE;++i){                builder.append("a");                Thread.sleep(100);            }        }catch(InterruptedException e){            System.out.println("Thread was interrupted");        }        return builder.toString();    }}

And then:

        ExecutorService service = Executors.newFixedThreadPool(1);    MyCallable myCallable = new MyCallable();    Future<String> futureResult = service.submit(myCallable);    String result = null;    try{        result = futureResult.get(1000, TimeUnit.MILLISECONDS);    }catch(TimeoutException e){        System.out.println("No response after one second");        futureResult.cancel(true);    }    service.shutdown();


The timeout on get() is for how long the 'client' will wait for the Future to complete. It does not have an impact on the future's execution.

Object result;int seconds = 0;while ((result = fut.get.(1, TimeUnit.SECOND)) == null) {    seconds++;    System.out.println("Waited " + seconds + " seconds for future";}


my callable will interrupt after the specified time(timeout) has passed

The above statement is wrong, Usually Future.get is blocking. Specifying the timeout allows you to use it in a non blocking manner.

This is useful for instance in time critical applications, if you need a result within let's say 2 seconds and receiving after that means you can't do anything with that.