Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a Future timeout kill the Thread execution

When using an ExecutorService and Future objects (when submitting Runnable tasks), if I specify a timeout value to the future's get function, does the underlying thread get killed when a TimeoutException is thrown?

like image 538
Nico Huysamen Avatar asked Apr 26 '13 08:04

Nico Huysamen


People also ask

How does Future cancel work?

cancel() will cancel any queued task or will call Thread. interrupt() on your thread if already running. It's your code's responsibility is to be ready for any interruptions.

What is future in Java thread?

Future , represents the result of an asynchronous computation. When the asynchronous task is created, a Java Future object is returned. This Future object functions as a handle to the result of the asynchronous task.


3 Answers

It does not. Why would it? Unless you tell it to.

There is a very valid concern here in case of a Callable for example. If you waited for the result for say 20 seconds and you did not get it, then you are not interested in the result anymore. At that time you should cancel the task at all.

Something like this:

Future<?> future = service.submit(new MyCallable());
    try {
        future.get(100, TimeUnit.MILLISECONDS);
    } catch (Exception e){
        e.printStackTrace();
        future.cancel(true); //this method will stop the running underlying task
    }
like image 171
Eugene Avatar answered Oct 23 '22 19:10

Eugene


No it doesnt. Morover there is even no attempt to interrupted the task. First of all Future.get with timeout doesn't say so. Secondly, try my test to see how it behaves

    ExecutorService ex = Executors.newSingleThreadExecutor();
    Future<?> f = ex.submit(new Runnable() {
        public void run() {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("finished");
        }
    });
    f.get(1, TimeUnit.SECONDS);

in 1 sec it prints

Exception in thread "main" java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:228)
    at java.util.concurrent.FutureTask.get(FutureTask.java:91)
    at Test1.main(Test1.java:23)

after another 1 sec the task successfullt finishes

finished
like image 18
Evgeniy Dorofeev Avatar answered Oct 23 '22 18:10

Evgeniy Dorofeev


It seems that you need to kill, cancel or shutdown the task explicitly

Handling exceptions from Java ExecutorService tasks

How do I get FutureTask to return after TimeoutException?

like image 5
gurvinder372 Avatar answered Oct 23 '22 17:10

gurvinder372