Question

I'm having some trouble with Java's ExecutorCompletionService hanging on program completion.

I need to use the ExecutorCompletionService rather than the ExecutorService because in my real program I'd like to set numerous tasks running and just take the result of the first one that completes.

Sadly I'm finding that my program still hangs, even if all Tasks have been processed.

I've created a small example that hangs when running.

import java.util.concurrent.*;

public class Debug {

    public static void main(String[] args) {
        CompletionService<String> compService = new ExecutorCompletionService<>(Executors.newFixedThreadPool(2));

        for (int i = 0; i < 2; i++) {
            compService.submit(new Task(i));
        }

        for (int i = 0; i < 2; i++) {
            try {
                String result = compService.take().get();
                System.out.println("RESULT: " + result);
            } catch (ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static class Task implements Callable<String> {

        private final int number;

        public Task(int number) {
            this.number = number;
        }

        @Override
        public String call() throws Exception {
            return "Number " + number;
        }
    }
}

If someone could point out what I'm doing wrong I'd be very grateful!

Thanks.

Was it helpful?

Solution

It hangs simply because you've started an executor, which uses threads, which keep running (waiting for new tasks to execute), until the executor is shut down:

    ExecutorService executor = Executors.newFixedThreadPool(2);
    CompletionService<String> compService = new ExecutorCompletionService<>(executor);

    for (int i = 0; i < 2; i++) {
        compService.submit(new Task(i));
    }

    for (int i = 0; i < 2; i++) {
        try {
            String result = compService.take().get();
            System.out.println("RESULT: " + result);
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    executor.shutdownNow();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top