ExecutorService that interrupts tasks after a timeout

You can use a ScheduledExecutorService for this. First you would submit it only once to begin immediately and retain the future that is created. After that you can submit a new task that would cancel the retained future after some period of time. ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); final Future handler = executor.submit(new Callable(){ … }); … Read more

ExecutorService, how to wait for all tasks to finish

The simplest approach is to use ExecutorService.invokeAll() which does what you want in a one-liner. In your parlance, you’ll need to modify or wrap ComputeDTask to implement Callable<>, which can give you quite a bit more flexibility. Probably in your app there is a meaningful implementation of Callable.call(), but here’s a way to wrap it … Read more

How to wait for all threads to finish, using ExecutorService?

Basically on an ExecutorService you call shutdown() and then awaitTermination(): ExecutorService taskExecutor = Executors.newFixedThreadPool(4); while(…) { taskExecutor.execute(new MyTask()); } taskExecutor.shutdown(); try { taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { … }

Java Timer vs ExecutorService?

According to Java Concurrency in Practice: Timer can be sensitive to changes in the system clock, ScheduledThreadPoolExecutor isn’t. Timer has only one execution thread, so long-running task can delay other tasks. ScheduledThreadPoolExecutor can be configured with any number of threads. Furthermore, you have full control over created threads, if you want (by providing ThreadFactory). Runtime … Read more