Is ScheduledThreadPoolExecutor ok for doing multiple tasks at same time?

java, scheduled-tasks

Solution

The way a ScheduledThreadPoolExecutor works is there is a single "scheduling" or master thread which checks for tasks to execute.

If it finds a task, it delegates it to a "worker" thread from the pool.

If multiple tasks are ready to be executed, they are "kicked off" one at a time, though once "kicked off", subsequent processing is concurrent, per Java's definition.

If you have two tasks that are both scheduled through the executor for the same time, the order in which they complete could vary from run to run and unless you put in specific controls such as locks, waits, etc... to handle this, it's up to java's thread scheduling (how java allots time to threads on a core) to determine how and when what gets processed. Please note that setting up such locks, waits, etc... is a deceptively complex task prone to race conditions leading to unexpected deadlocks, live locks, etc...

Problem

The docs for `ScheduledThreadPoolExecutor` says that - Tasks scheduled for exactly the same execution time are enabled in first-in-first-out (FIFO) order of submission. Does this mean that the tasks which SHOULD be done at the same time are never done at the same time. Instead they are executed in FIFO order ? If that is true then which class do I use which is better than `Timer` and also does not have this FIFO problem ?

Original source