instanceOfObject
instanceOfObject

Reputation: 2984

Terminate underlying thread with future.cancel() to re-use the thread

public class TestThreadTerminate {
    public static void main(String args[]) throws Exception {
        ExecutorService e = Executors.newCachedThreadPool();
        Future<Boolean> f = e.submit(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                System.out.println("Step 1!!");
                Thread.sleep(5000);
                System.out.println("Step 2!!");
                Thread.sleep(5000);
                System.out.println("Step 3!!");
                return true;
            }
        });
        try {
            Boolean flag = f.get(1, TimeUnit.SECONDS);
        } catch(TimeoutException ex) {
            f.cancel(true);
            System.out.println("Canceling");
        }
        System.out.println("FINAL!");
    }
}

With this, my output is

Step 1
Canceling
Final

But program terminates a lot later. Why does it happen once thread is interrupted?

If I remove f.cancel(true), my thread keeps running and prints following:

Step 1
Canceling
Final
Step 2
Step 3

What can I do to terminate the program i.e to terminate the inner thread? Effectively, I want to use this thread for other tasks in the thread pool which doesn't seem to be happening here.

Putting Thread.currentThread().isInterrupted() at all the places before returning doesn't look like a good idea.

Upvotes: 1

Views: 724

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

Why does it happen once thread is interrupted?

This is because your thread pool is still active - potentially, it could accept another runnable/callable to be executed, so it waits to see if this happens before cleaning up the unused threads in the pool.

The default timeout on a cached thread pool is 60 seconds - does this match up with what you have seen?

If you want it to shut down more quickly, you should call e.shutdown().

Upvotes: 2

Related Questions