Newbie Newbie - 3 months ago 39
Java Question

ExecutorService for do while loop in java

I am new to concurrency and I was trying to implement executor service concurrency for a do-while loop.
But i always run into

RejeectedExecutionException

Here is my sample code -

do {

Future<Void> future = executor.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
// action
return null;
}
});
futures.add(future);
executor.shutdown();
for (Future<Void> future : futures) {
try {
future.get();
} catch (InterruptedException e) {
throw new IOException(e)
}
}
}
while (true);


But this seems incorrect. I think I am calling the shutdown at the wrong place. Can anyone please help me implement
Executor Service in a do-while
loop correctly .
Thanks.

Answer

ExecutorService.shutdown() stops the ExecutorService from accepting anymore jobs. It should be called when you're done submitting jobs.

Also Future.get() is a blocking method, which means it will block the execution of current thread and next iteration of loop will not continue unless this future (on which the get is called) returns. This will happen in every iteration, which makes the code non parallel.

You can use a CountDownLatch to wait for all the jobs to return.

Following is the correct code.

final List<Object> results = Collections.synchronizedList(new ArrayList<Object>());
final CountDownLatch latch = new CountDownLatch(10);//suppose you'll have 10 futures

do {
    Future<Void> future = executor.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            // action
            latch.countDown();//decrease the latch count
            results.add(result); // some result
            return null;
        }
    });

    futures.add(future);
} while (true);

executor.shutdown();

latch.await(); //This will block till latch.countDown() has been called 10 times.

//Now results has all the outputs, do what you want with them.

Also if you're working with Java 8 then you can take a look at this answer http://stackoverflow.com/a/36261808/5343269