Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no scheduled cached thread pool provided by the Java Executors class?

Executors provides newCachedThreadPool() and newScheduledThreadPool(), but not newCachedScheduledThreadPool(), what gives here? I have an application that receives bursty messages and needs to schedule a fairly lengthy processing step after a fixed delay for each. The time constraints aren't super tight, but I would prefer to have more threads created on the fly if I exceed the pool size and then have them trimmed back during periods of inactivity. Is there something I've missed in the concurrent library, or do I need to write my own?

like image 447
BD at Rivenhill Avatar asked Jul 19 '10 13:07

BD at Rivenhill


People also ask

What is scheduled thread pool executor?

ScheduledThreadPoolExecutor class in Java is a subclass of ThreadPoolExecutor class defined in java. util. concurrent package. As it is clear from its name that this class is useful when we want to schedule tasks to run repeatedly or to run after a given delay for some future time. It creates a fixed-sized Thread Pool.

What is cached thread pool in Java?

A cached thread pool is useful when tasks submitted for processing should not wait and needs to be addressed as soon as submitted. To satisfy this requirement, Java creates a new thread for the submitted task if there are no thread in the pool to address the task. A cached thread pool can have up to 2³¹ no of threads.

How do you create a thread pool in Java?

To use thread pools, we first create a object of ExecutorService and pass a set of tasks to it. ThreadPoolExecutor class allows to set the core and maximum pool size. The runnables that are run by a particular thread are executed sequentially.

What's the difference between Cachedpool and Fixedthreadpool of executor service?

As opposed to the cached thread pool, this one is using an unbounded queue with a fixed number of never-expiring threads. Therefore, instead of an ever-increasing number of threads, the fixed thread pool tries to execute incoming tasks with a fixed amount of threads.


1 Answers

By design the ScheduledThreadPoolExecutor is a fixed size. You can use a single threaded version that submits to a normal ExecutorService for performing the task. This event thread + worker pool is fairly ease to coordinate and the flexibility makes up for the dedicated thread. I've used this in the past to replace TimerTasks and other non-critical tasks to utilize a common executor as a system-wide pool.

like image 78
Ben Manes Avatar answered Sep 24 '22 20:09

Ben Manes