Or should I use a different strategy to schedule this tasks.
Yes, you should use another strategy.
As the same suggests, a ScheduledExecutorService
is for scheduling to run a task after a certain amount of time has passed. If you do not know when a task
If you want to buffer some tasks to be executed at a later undetermined time, collect your Runnable
or Callable
objects as you would any other bunch of objects. Use a class from the Java Collections framework.
If you care about the tasks being run in a particular order, such as LIFO or FIFO, use a Queue
or Deque
implementation.
When the time arrives to run your tasks, feed the Runnable
/Callable
objects from the queue/deque and submit to an executor service.
- If you care about the tasks running serially, and not overlapping their executions in time, then use a single-threaded executor service.
ExecutorService es = Executors.newSingleThreadExecutor() ;
- If, instead, you care about getting a bunch of tasks done as soon as possible, then you might want to use an executor service backed by a thread pool. This assumes your deployment machine has multiple cores, and/or your your tasks are not CPU-bound (the tasks spend significant time waiting on resources such as network calls, reading/writing to storage drives, database queries, etc.).
ExecutorService es = Executors.newCachedThreadPool() ;
ExecutorService es = Executors.newFixedThreadPool( 4 ) ;
Obligatory tip: Read, re-read, and study the superb book, Java Concurrency in Practice by Brian Goetz, et al.