This class is used to execute tasks in Java. Generally, users will not directly create a ThreadPoolExecutor, but instead use one of the the static factory methods in `Executors` to create one. For example:
class Runner { private final ExecutorService executor = Executors.newCachedThreadPool(); executor.execute(r); } }
ThreadPoolExecutor is implemented by two sets of queues:
If there are no items to take off the task queue, the threads wait to try and take the next item that gets added. In this way, they form a natural queue, each waiting in line to get the next task to execute.
When submitting a work item to a ThreadPoolExecutor, the caller tries to add the item to the task queue. What happens if there is no room on the task queue? ThreadPoolExecutor tries to spawn a new thread to accept the new task. The behavior here is different depending on the core pool size.
As we can see, the core pool size has an intricate interplay with the task queue. By constraining the task queue, we can make ThreadPoolExecutor spawn more threads, up to the maximum. By unbounding the task queue, we can limit the number of threads handling tasks. By default, a cached threadpool is both an unlimited number of thread, and a limited task queue. A fixed threadpool is an unlimitted number of tasks, and a limited thread pool. The constructor overloads of ThreadPoolExecutor let us customize this even more, but these are the most common cases. The behavior of the pool is a consequence of the task queue and thread spawning rules.
This class is similar to ThreadPoolExecutor, but doesn't allow you to change the task queue. The task queue is a priority queue, sorted on the task deadline.
A consequence of not being able to bound the queue is that the thread count is more important:
scheduleAtFixedRate() and scheduleWithFixedDelay(). These tasks will not be run in a timely manner.