i currently have a list of classes every class starts a scheduler like this:
private ScheduledFuture<?> myTask;
private ScheduledExecutorService scheduler;
public startScheduler() {
scheduler = Executors.newScheduledThreadPool( 1 );
myTask = scheduler.scheduleAtFixedRate(new Runnable() {
// doing work here
},
delay,
interval,
TimeUnit.MILLISECONDS );
}
So every class basically starts it’s own scheduler and only has one task. But as i understand now a scheduler can take and run more tasks in parallel. The tasks (or in my current program the schedulers) have different delay and interval values and the number of schedulers started is unknown to me (cause the user can start new ones and stop running ones). All schedulers run in parallel. So should i change my code in order to use only one scheduler? Should I prefer the “CachedThreadPool”?
Yes, you can use just one pool to schedule all your tasks. Also, if you need the ability to schedule tasks at time intervals as you are currently doing, you should stick with
newScheduledThreadPoolbecausenewCachedThreadPoolreturns only anExecutorServiceinterface and notScheduledExecutorService.