Phate
Phate

Reputation: 6622

FutureTask stays active

This is a very simple code:

FutureTask<Integer> task = new FutureTask<>(new
            Callable<Integer>(){
                @Override
                public Integer call() throws Exception {
                    int i =0;
                    while(i<10){
                        i++;
                    }

                    return 0;
                }

    });

counts 10 then exits...easy.

I execute it like this:

    Executor executor = Executors.newCachedThreadPool();
    executor.execute(task);
    try {
        task.get(3000, TimeUnit.MILLISECONDS);
        System.out.println("Everything was ok");
    } catch (InterruptedException | ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TimeoutException ex){
        boolean result = task.cancel(true); 
        System.out.println("the task has timed out "+result);
    }

I get "everything was ok" into the console, so the task correctly executes and returns. However the thread still survives! I can see it by executing it into eclipse: the red square, marking an executing program, is still active. But my main closes after printing "everything was ok", so it must be that task. Why it does not close? How can I close it?

I saw some examples with ExecutorService class which has a shutdown method, but I don't want to shutdown the entire thread pool because I still need it active to accept other tasks, I just want THAT task to shutdown!

Upvotes: 3

Views: 139

Answers (1)

dcsohl
dcsohl

Reputation: 7406

The documentation for Executors.newCachedThreadPool() states that it "Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available ... Threads that have not been used for sixty seconds are terminated and removed from the cache."

Have you waited sixty seconds?

Upvotes: 3

Related Questions