Is having a single threadpool better design than multiple threadpools

The purpose of having separate dedicated threadpools is so that an activity doesn’t get starved for threads because other activities took all the threads. If some service has its own threadpool then it is assured of having a certain number of threads at its disposal and it’s not as sensitive to demands made by other … Read more

How to wait for all tasks in an ThreadPoolExecutor to finish without shutting down the Executor?

If you are interested in knowing when a certain task completes, or a certain batch of tasks, you may use ExecutorService.submit(Runnable). Invoking this method returns a Future object which may be placed into a Collection which your main thread will then iterate over calling Future.get() for each one. This will cause your main thread to … Read more

How to properly use Java Executor?

ExecutorService ExecutorService executor=Executors.newFixedThreadPool(50); It is simple and easy to use. It hides low level details of ThreadPoolExecutor. Prefer this one when number of Callable/Runnable tasks are small in number and piling of tasks in unbounded queue does not increase memory & degrade the performance of the system. If you have CPU/Memory constraints, use ThreadPoolExecutor with … Read more

How to get the ThreadPoolExecutor to increase threads to max before queueing?

How can I work around this limitation in ThreadPoolExecutor where the queue needs to be bounded and full before more threads will be started. I believe I have finally found a somewhat elegant (maybe a little hacky) solution to this limitation with ThreadPoolExecutor. It involves extending LinkedBlockingQueue to have it return false for queue.offer(…) when … Read more

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

I think the docs explain the difference and usage of these two functions pretty well: newFixedThreadPool Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, … Read more

Handling exceptions from Java ExecutorService tasks

WARNING: It should be noted that this solution will block the calling thread. If you want to process exceptions thrown by the task, then it is generally better to use Callable rather than Runnable. Callable.call() is permitted to throw checked exceptions, and these get propagated back to the calling thread: Callable task = … Future … Read more