Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Schedule periodic tasks in Java, avoid creating new threads until necessary (like CachedThreadPool)

I have a number of tasks that I would like to execute periodically at different rates for most tasks. Some of the tasks may be scheduled for simultaneous execution though. Also, a task may need to start executing while another is currently executing.

I would also like to customize each task by setting an object for it, on which the task will operate while it is being executed.

Usually, the tasks will execute in periods of 2 to 30 minutes and will take around 4-5 seconds, sometimes up to 30 seconds when they are executed.

I've found Executors.newSingleThreadedScheduledExecutor(ThreadFactory) to be almost exactly what I want, except that it might cause me problems if a new task happens to be scheduled for execution while another is already executing. This is due to the fact that the Executor is backed up by a single execution thread.

The alternative is to use Executors.newScheduledThreadPool(corePoolSize, ThreadFactory), but this requires me to create a number of threads in a pool. I would like to avoid creating threads until it is necessary, for instance if I have two or more tasks that happen to need parallell executing due to their colliding execution schedules.

For the case above, the Executors.newCachedThreadPool(ThreadFactory) appears to do what I want, but then I can't schedule my tasks. A combination of both cached and scheduled executors would be best I think, but I am unable to find something like that in Java.

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

like image 598
veroslav Avatar asked Oct 04 '12 08:10

veroslav


2 Answers

Isn't ScheduledThreadPoolExecutor.ScheduledThreadPoolExecutor(int):

ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(0);

what you need? 0 is the corePoolSize:

corePoolSize - the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set

like image 158
Tomasz Nurkiewicz Avatar answered Oct 19 '22 01:10

Tomasz Nurkiewicz


I guess you will not able to do that with ScheduledExecutor, because it uses DelayedWorkQueue where as newCachedThreadPool uses ThreadPoolExecutor SynchronousQueue as a work queue.

So you can not change implementation of ScheduledThreadPoolExecutor to act like that.

like image 37
Amit Deshpande Avatar answered Oct 19 '22 03:10

Amit Deshpande