Home > database >  Program won't exit in using Callable and Future
Program won't exit in using Callable and Future

Time:09-26

IDE: IntelliJ
JDK: Java 11

While was testing a sample code from lecture, I have found something really weird that my program just won't stop, even though there aren't any loop!

import java.util.concurrent.Callable;

public class FindMaxTask implements Callable<Integer> {
    private int[] data;
    private int start;
    private int end;

    public FindMaxTask(int[] data, int start, int end) {
        this.data = data;
        this.start = start;
        this.end = end;
    }

    public Integer call() {
        int max = Integer.MIN_VALUE;
        for (int i = start; i < end; i  ) {
            if (data[i] > max) {
                max = data[i];
            }
        }
        return max;
    }
}

This is a FindMaxTask that implements Callable interface which performs a finding maximum value in given range of array.

public static void testCallable() throws ExecutionException, InterruptedException {
        final int dataSize = 10000;
        int[] data = new int[dataSize];
        Random random = new Random();

        for (int i = 0; i < dataSize; i  ) {
            data[i] = random.nextInt(1000000);
        }

        FindMaxTask task0 = new FindMaxTask(data, 0, dataSize / 2);
        FindMaxTask task1 = new FindMaxTask(data, dataSize / 2, dataSize);

        ExecutorService service = Executors.newFixedThreadPool(2);

        Future<Integer> future0 = service.submit(task0);
        Future<Integer> future1 = service.submit(task1);

        int ret0 = future0.get();
        int ret1 = future1.get();

        System.out.println("ret0: "   ret0   System.lineSeparator()   "ret1: "   ret1);
    }

This is a testCallable static function in Main class.

If I run testCallable function in main function, program just stops after printing each ret value in console.

Is this problem has something to do with Callable or Future? (I have tried debugging future1.isDone() with value of true after printing ret0,ret1 so it clearlly doesn't seems like that chlid thread has been blocked)
Please give me an advise why is this happening

CodePudding user response:

You have to shut down the thread pool. Otherwise, you still have non-daemon threads running in the background. The JVM doesn't exit until all non-daemon threads have stopped.

ExecutorService service = Executors.newFixedThreadPool(2);
try {
    // do things with the executor service
} finally {
    service.shutdown();
}

If you want to block until all tasks have completed, you can use awaitTermination, or call shutdown and then loop until isTerminated returns true. If you want to try to terminate any running or queued tasks immediately, you can use shutdownNow.

  • Related