Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ScheduledThreadPoolExecutor ok for doing multiple tasks at same time?

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 ?

like image 719
Time Avatar asked Mar 11 '13 18:03

Time


People also ask

Can a thread have multiple tasks?

Operating system task scheduling Threads are the smallest units of processing that can be executed by an operating system, and allow the application logic to be separated into several concurrent execution paths. Threads are useful when complex applications have many tasks that can be performed at the same time.

What is ScheduledThreadPoolExecutor in Java?

ScheduledThreadPoolExecutor class in Java is a subclass of ThreadPoolExecutor class defined in java. util. concurrent package. As it is clear from its name that this class is useful when we want to schedule tasks to run repeatedly or to run after a given delay for some future time. It creates a fixed-sized Thread Pool.

What is the use of TaskExecutor in spring?

The TaskExecutor was originally created to give other Spring components an abstraction for thread pooling where needed. Components such as the ApplicationEventMulticaster , JMS's AbstractMessageListenerContainer , and Quartz integration all use the TaskExecutor abstraction to pool threads.

What is spring boot executor?

Spring 2.0 introduces a new abstraction for dealing with executors. Executors are the Java 5 name for the concept of thread pools. The "executor" naming is due to the fact that there is no guarantee that the underlying implementation is actually a pool; an executor may be single-threaded or even synchronous.


1 Answers

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...

like image 123
Taylor Avatar answered Sep 19 '22 02:09

Taylor