ExecutorService vs CompletableFuture

Functionally, the two approaches are more or less the same: you submit your tasks for execution; you don’t wait for the result. Technically, however, there are some subtle differences: In the second approach, you didn’t specify an executor, so it will use the common ForkJoinPool. You would have to pass an executor as second argument … Read more

Java ExecutorService: awaitTermination of all recursively created tasks

This really is an ideal candidate for a Phaser. Java 7 is coming out with this new class. Its a flexible CountdonwLatch/CyclicBarrier. You can get a stable version at JSR 166 Interest Site. The way it is a more flexible CountdownLatch/CyclicBarrier is because it is able to not only support an unknown number of parties … Read more

Thread.join() equivalent in executor [duplicate]

You shouldn’t use executor like this if you want to wait for tasks to finish. What if you don’t want/can’t shutdown your thread pool executor? This is a more recommended way: ExecutorService exec = Executors.newFixedThreadPool(3); Collection<Future<?>> tasks = new LinkedList<Future<?>>(); Future<T> future = exec.submit(A); tasks.add(future); future = exec.submit(B); tasks.add(future); future = exec.submit(C); tasks.add(future); // wait … Read more

Program does not terminate immediately when all ExecutorService tasks are done

Executors.newCachedThreadPool() uses Executors.defaultThreadFactory() for its ThreadFactory. defaultThreadFactory‘s javadocs say that “each new thread is created as a non-daemon thread” (emphasis added). So, the threads created for the newCachedThreadPool are non-daemon. That means that they’ll prevent the JVM from exiting naturally (by “naturally” I mean that you can still call System.exit(1) or kill the program to … Read more

Controlling Task execution order with ExecutorService

I write own Executor that warrants task ordering for tasks with same key. It uses map of queues for order tasks with same key. Each keyed task execute next task with the same key. This solution don’t handle RejectedExecutionException or other exceptions from delegated Executor! So delegated Executor should be “unlimited”. import java.util.HashMap; import java.util.LinkedList; … Read more

How to check if all tasks running on ExecutorService are completed

There isn’t a clean way to check if all Runnables are done if you use ExecutorService.execute(Runnable). Unless you build a mechanism to do so in the Runnable itself (which is sloppy in my opinion). Instead: Use ExecutorService.submit(Runnable). This method will return a Future<?> which is a handle to the result of a Runnable. Using Futures … Read more

tech