Schedule periodic jobs in Java, avoid creating new threads as needed (for example, CachedThreadPool)

I have a number of tasks that I would like to perform periodically at different rates for most tasks. However, some of the tasks may be scheduled for simultaneous execution. In addition, a task may need to be started while another is running.

I would also like to configure each task by setting an object for it on which the task will work during its execution.

Typically, tasks are performed in periods of 2 to 30 minutes and take about 4-5 seconds, sometimes up to 30 seconds, when they are completed.

I found Executors.newSingleThreadedScheduledExecutor(ThreadFactory) almost exactly what I want, except that it can cause me problems if a new task is scheduled for execution and another is already in progress. This is due to the fact that the Contractor was standby using a single thread of execution.

An alternative is to use Executors.newScheduledThreadPool(corePoolSize, ThreadFactory) , but this requires me to create multiple threads in the pool. I would like to avoid creating threads until it is needed, for example, if I have two or more tasks that require parallel operations due to their colliding execution schedules.

In the above case, Executors.newCachedThreadPool(ThreadFactory) seems to do what I want, but then I cannot plan my tasks. It would be best to combine both cached and scheduled artists, but I can't find something like this in Java.

What would be the best way to implement the above, do you think?

+7
source share
2 answers

Not ScheduledThreadPoolExecutor.ScheduledThreadPoolExecutor(int) :

 ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(0); 

what you need? 0 is corePoolSize :

corePoolSize - the number of threads to store in the pool, even if they are inactive, if allowCoreThreadTimeOut not set

+1
source

I think you cannot do this with a ScheduledExecutor , because it uses a DelayedWorkQueue , where ThreadPoolExecutor SynchronousQueue is used as the work queue as newCachedThreadPool .

Therefore, you cannot change the implementation of ScheduledThreadPoolExecutor to act like this.

+1
source

All Articles