How to implement simple threading with a fixed number of worker Threads
This is a quick tutorial on implementing simple threading with a fixed number of worker Threads.
- If your task queue is not going to be unbounded and tasks can complete in shorter time intervals, you can use Executors.newFixedThreadPool(n); as suggests by experts.
- The only drawback in this solution is unbounded task queue size. You don’t have control over it. The huge pile-up in task queue will degrade performance of application and may cause out of memory in some scenarios.
If you want to use ExecutorService and enable work stealing mechanism where idle worker threads share the work load from busy worker threads by stealing tasks in task queue. It will return ForkJoinPool type of Executor Service.
- public static ExecutorService newWorkStealingPool(int parallelism)
- Creates a thread pool that maintains enough threads to support the given parallelism level, and may use multiple queues to reduce contention. The parallelism level corresponds to the maximum number of threads actively engaged in, or available to engage in, task processing. The actual number of threads may grow and shrink dynamically. A work-stealing pool makes no guarantees about the order in which submitted tasks are executed.
- I prefer ThreadPoolExecutor due to flexibility in APIs to control many paratmeters, which controls the flow task execution.
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
In your case, set both corePoolSize and maximumPoolSize as N. Here you can control task queue size, define your own custom thread factory and rejection handler policy.