Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java program not terminating

The code below checks the usage of ExecutorCompletionService from Java Concurrency framework (the IDE being used is Netbeans).

But the program doesn't terminate. Why?

Code:

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;

public class TestFuture {

    public static void main(String... args) throws InterruptedException, ExecutionException {
        Executor ex = Executors.newCachedThreadPool();
        CompletionService<Long> cs = new ExecutorCompletionService<Long>(ex);
        cs.submit(new Worker());
        cs.submit(new Worker());
        cs.submit(new Worker());
        for (int i = 0; i < 3; i++) {
            long l = cs.take().get();
            //utilize the result
            System.out.println(l);
        }
    }
}

class Worker implements Callable {

    @Override
    public Long call() throws Exception {
        //do some task and return back
        return System.currentTimeMillis();
    }
}
like image 218
Ankit Kumar Avatar asked Oct 20 '25 16:10

Ankit Kumar


1 Answers

Threads in thread pool will keep running when main is finished. That's why JVM won't shut down. You need to either use daemon-threads, or shutdown the pool explicitly.

Here's an example:

ExecutorService ex = Executors.newCachedThreadPool();
// do all your submission work here
ex.shutdown();
like image 188
Andrew Logvinov Avatar answered Oct 23 '25 05:10

Andrew Logvinov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!