Difference between fixed and cached thread pool in Java
Here are key difference between a fixed and cached thread pools in Java.
1. When you submit a task they are immediately executed in cached thread but they can be placed in a queue, if no thread is free in case of fixed thread pool. This means, if you want guaranteed and immediate execution then using a cached thread pool is better option but if you are resource constraint and want to use fixed number of threads then fixed thread pool is a better choice.
2. You can use Executors.newCachedThreadPool() factory method to create a cached pool in Java and Executors.newFixedThreadPool() to create fixed thread pool. Bot methods are part of Java Concurrency API and defined in Executors utility class.
3. Cached thread pool can create more threads if required, but no extra threads are created in fixed thread pool. This means cached thread pool is a better choice if you have resources as it can create and increase number of threads in the pool if load increases but fixed thread pool is a better choice in case of resource constraint environment.
Example of Fixed Thread Pool
Here is an example of Fixed thread pool in Java:
Example of Cached Thread Pool
Here is an example of cached thread pool in Java:
If you want to remember the difference then just remember their name, a fixed thread pools means number of threads in the pool is fixed while in case of cached thread pool, number of threads can increase or decrease depending upon load.
Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.
P.S. - If you are new into Java Multithreading and Concurrency and need a free online training course to learn Multithreading and Concurrency basics then I also suggest you check out this Java Multithreading a free course on Udemy. It's completely free and all you need is a free Udemy account to join this course.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.