294. Design a Thread Pool Executor
Asked in
Design a Thread Pool Executor
Design a simulation of a thread pool executor. Nothing runs in parallel and no real operating system threads are created. Time only moves forward when runOneStep() is called, and each call is one unit of time, called a step.
The pool holds named threads and a bounded FIFO queue of tasks waiting for a thread. You add threads yourself, submit tasks, move time forward one step at a time, and finally shut the pool down.

Key Terms

  • ThreadPoolExecutor: owns the threads, the task queue and the executor state.
  • Worker: one named thread: its state, its current task and its idle time.
  • Task: a unique task ID and the number of steps it still needs.
  • Thread states
    • IDLE: has no task.
    • RUNNING: working on a task.
    • STOPPING: working on its last task. It is removed as soon as that task finishes and never gets another task.
  • Active threads: every thread currently in the pool, in any state, STOPPING included. Name uniqueness, maximumPoolSize and corePoolSize are all checked against the active threads.
  • Idle time: how many whole steps a thread has been idle. It starts at 0 and goes back to 0 whenever the thread gets a task or finishes one.
  • Name order: thread names are compared as plain, case-sensitive strings, character by character, so "B" < "a" and "t10" < "t2". "Smallest", "largest" and "in name order" always refer to this order.

Executor States

  • RUNNING: the starting state. Threads and tasks can be added.
  • SHUTTING_DOWN: after a successful shutdown(). No new threads or tasks are accepted, but running and queued tasks still finish.
  • TERMINATED: shutdown is complete: no threads and no queued tasks are left. Nothing changes after this.
Below, "shutdown has started" means the executor is SHUTTING_DOWN or TERMINATED.

Method Signatures

Constructor

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, int keepAliveSteps, int queueCapacity, String rejectionPolicy)
  • corePoolSize: keep-alive never shrinks the pool below this many active threads. (Shutting down a thread or the executor can.)
  • maximumPoolSize: the pool never holds more active threads than this.
  • keepAliveSteps: how many steps a thread may stay idle before keep-alive can remove it.
  • queueCapacity: the most tasks that can wait in the queue.
  • rejectionPolicy: what to do with a new task when the queue is full.
The executor starts in RUNNING with no threads and an empty queue. Threads are never created automatically; only addThread creates them.

Add a Thread

boolean addThread(String threadName)
  • Adds a new IDLE thread with idle time 0 and returns true.
  • Returns false and changes nothing if shutdown has started, an active thread already has this name, or there are already maximumPoolSize active threads.
  • The new thread does not take a queued task right away. It joins task assignment in the next runOneStep().
  • A name can be used again after its thread has been removed.

Shut Down a Thread

boolean shutdownThread(String threadName)
  • IDLE thread: it is removed immediately and the method returns true. This removal produces no REMOVED event.
  • RUNNING thread: it becomes STOPPING and the method returns true. It finishes its current task and is then removed by runOneStep().
  • Returns false and changes nothing if shutdown has started, the thread does not exist, or it is already STOPPING.

Submit a Task

String submitTask(String taskId, int durationSteps)
Check these rules in order and apply the first one that matches:
  1. Shutdown has started → return "REJECTED". The rejection policy is not used.
  2. The queue is empty and some thread is IDLE → start the task now on the smallest-named idle thread and return "STARTED:threadName".
  3. The queue has space → add the task to the back of the queue and return "QUEUED".
  4. The queue is full → apply the rejection policy and return its result.
  • If tasks are already waiting, a new task always goes behind them, even if an idle thread exists (this can happen right after addThread). If the queue is full in that case, the rejection policy applies.
  • A task started here does its first step of work in the next runOneStep(). No STARTED event is produced for it later.

Rejection Policies

Used only when a task arrives and the queue is full.
  • ABORT: drop the new task and return "REJECTED".
  • DISCARD: drop the new task and return "DISCARDED".
  • CALLER_RUNS: the caller runs the task instantly; return "CALLER_RAN". The task never enters the pool.
  • DISCARD_OLDEST: drop the task at the front of the queue, add the new task to the back, and return "QUEUED:DROPPED:droppedTaskId".
Dropped, rejected and caller-run tasks never appear in getState() and never produce events.

Run One Step

List<String> runOneStep()
Moves time forward by one step. If the executor is TERMINATED, do nothing and return an empty list. Otherwise run these phases in order:
  1. Work. Every thread that had a task when the call started (RUNNING or STOPPING) does one step of work: its task's remaining steps go down by 1.
  2. Finish. For every task that reaches 0, add "COMPLETED:threadName:taskId". If its thread is STOPPING, remove the thread and add "REMOVED:threadName". Otherwise the thread becomes IDLE with idle time 0.
  3. Assign. Go through all IDLE threads in name order, including threads that just finished and threads added since the last step. Give each one the task at the front of the queue, until the queue or the idle threads run out. Each of these threads becomes RUNNING with idle time 0; add "STARTED:threadName:taskId". These tasks start working in the next step.
  4. Count idle time. Add 1 to the idle time of every thread that was IDLE when the call started and is still IDLE. A thread that became idle during this call stays at 0.
  5. Keep-alive. While there are more than corePoolSize active threads and some IDLE thread has idle time ≥ keepAliveSteps, remove the largest-named such thread and add "REMOVED:threadName".
  6. Shutdown cleanup (only if shutdown has started). If the queue is empty, remove every IDLE thread and add "REMOVED:threadName" for each. Then, if no threads and no queued tasks are left, the executor becomes TERMINATED.
  7. Return the events of this step, sorted as described below, or an empty list if nothing happened.
Event order and notes:
  • Sort events by thread name. Compare the names themselves, not the whole event strings: "STARTED:a:..." comes before "COMPLETED:b:...".
  • If a thread has two events in one step, they are COMPLETED followed by either STARTED or REMOVED. A thread is never both started and removed in the same step.
  • When keepAliveSteps = 0, a thread can finish its task and be removed by keep-alive in the same step, as long as it did not get a new task.

Shut Down the Executor

boolean shutdown()
  • Returns false if shutdown has already started.
  • Returns false if tasks are waiting in the queue but no thread can ever take them, because there are no threads or every thread is STOPPING. Nothing changes and the executor stays RUNNING.
  • Otherwise returns true:
    • If there are no threads and the queue is empty, the executor becomes TERMINATED right away.
    • Otherwise it becomes SHUTTING_DOWN. Running and queued tasks carry on as normal. Idle threads are not removed by shutdown() itself; the shutdown cleanup in the next runOneStep() removes them.

Get Current State

List<String> getState()
Returns a snapshot and changes nothing. The list contains, in order:
  1. "EXECUTOR:RUNNING", "EXECUTOR:SHUTTING_DOWN" or "EXECUTOR:TERMINATED".
  2. One entry per active thread, in name order:
    • "THREAD:threadName:IDLE:idleSteps"
    • "THREAD:threadName:RUNNING:taskId:remainingSteps"
    • "THREAD:threadName:STOPPING:taskId:remainingSteps"
  3. One "QUEUED:taskId" entry per waiting task, front of the queue first. Nothing is added when the queue is empty.
A terminated executor returns exactly ["EXECUTOR:TERMINATED"].

Ordering Rules at a Glance

  • Task started by submitTask: the smallest-named idle thread.
  • Queued tasks in runOneStep: oldest task first, to idle threads in name order.
  • Keep-alive removals: the largest-named eligible thread first.
  • Events: by thread name; a thread's COMPLETED comes before its STARTED or REMOVED.
  • getState: threads in name order, then queued tasks oldest first.

Constraints

  • 1 ≤ corePoolSize ≤ maximumPoolSize ≤ 1,000
  • 0 ≤ keepAliveSteps ≤ 1,000,000
  • 1 ≤ queueCapacity ≤ 100,000
  • 1 ≤ threadName.length() ≤ 100
  • 1 ≤ taskId.length() ≤ 100
  • 1 ≤ durationSteps ≤ 1,000,000
  • rejectionPolicy is one of "ABORT", "DISCARD", "CALLER_RUNS" or "DISCARD_OLDEST".
  • Thread names and task IDs contain only letters, digits, underscores and hyphens, and are case-sensitive.
  • Every task ID passed to submitTask is unique for the lifetime of the executor, including rejected and discarded tasks.

Examples

Example 1: the basics

  1. ThreadPoolExecutor(corePoolSize = 1, maximumPoolSize = 3, keepAliveSteps = 2, queueCapacity = 1, rejectionPolicy = "ABORT")
  2. addThread(threadName = "thread-2") returns true.
  3. addThread(threadName = "thread-1") returns true.
  4. submitTask(taskId = "compile", durationSteps = 2) returns "STARTED:thread-1". Both threads are idle and thread-1 is the smaller name.
  5. submitTask(taskId = "search", durationSteps = 1) returns "STARTED:thread-2".
  6. submitTask(taskId = "backup", durationSteps = 2) returns "QUEUED". No thread is idle.
  7. getState() returns ["EXECUTOR:RUNNING", "THREAD:thread-1:RUNNING:compile:2", "THREAD:thread-2:RUNNING:search:1", "QUEUED:backup"].
  8. runOneStep() returns ["COMPLETED:thread-2:search", "STARTED:thread-2:backup"]. Both tasks do one step of work, search finishes, and the freed thread-2 picks up backup, which starts working in the next step.
  9. getState() returns ["EXECUTOR:RUNNING", "THREAD:thread-1:RUNNING:compile:1", "THREAD:thread-2:RUNNING:backup:2"].

Example 2: keep-alive, a full queue, stopping a thread, shutdown

  1. ThreadPoolExecutor(corePoolSize = 2, maximumPoolSize = 3, keepAliveSteps = 1, queueCapacity = 1, rejectionPolicy = "DISCARD_OLDEST")
  2. addThread(threadName = "a") returns true.
  3. addThread(threadName = "b") returns true.
  4. addThread(threadName = "c") returns true.
  5. addThread(threadName = "d") returns false. The pool already has maximumPoolSize (3) threads.
  6. submitTask(taskId = "t1", durationSteps = 1) returns "STARTED:a".
  7. runOneStep() returns ["COMPLETED:a:t1", "REMOVED:c"]. t1 finishes, so a becomes idle with idle time 0. b and c were idle for the whole step, so their idle time becomes 1, which reaches keepAliveSteps. With 3 threads and corePoolSize 2, keep-alive removes the largest-named eligible thread, c. That leaves 2 threads, so b stays.
  8. getState() returns ["EXECUTOR:RUNNING", "THREAD:a:IDLE:0", "THREAD:b:IDLE:1"].
  9. submitTask(taskId = "t2", durationSteps = 2) returns "STARTED:a".
  10. submitTask(taskId = "t3", durationSteps = 2) returns "STARTED:b".
  11. submitTask(taskId = "t4", durationSteps = 1) returns "QUEUED".
  12. submitTask(taskId = "t5", durationSteps = 1) returns "QUEUED:DROPPED:t4". The queue is full, so the oldest waiting task t4 is dropped and t5 takes its place.
  13. shutdownThread(threadName = "b") returns true. b is running, so it becomes STOPPING.
  14. getState() returns ["EXECUTOR:RUNNING", "THREAD:a:RUNNING:t2:2", "THREAD:b:STOPPING:t3:2", "QUEUED:t5"].
  15. runOneStep() returns []. Both tasks go from 2 to 1 remaining steps.
  16. shutdown() returns true. a is not stopping, so it can still run the queued t5.
  17. submitTask(taskId = "t6", durationSteps = 1) returns "REJECTED". Shutdown has started.
  18. runOneStep() returns ["COMPLETED:a:t2", "STARTED:a:t5", "COMPLETED:b:t3", "REMOVED:b"]. Both tasks finish. b was stopping, so it is removed, and a picks up t5. Events are ordered by thread name, so all of a's events come before b's.
  19. getState() returns ["EXECUTOR:SHUTTING_DOWN", "THREAD:a:RUNNING:t5:1"].
  20. runOneStep() returns ["COMPLETED:a:t5", "REMOVED:a"]. t5 finishes and the queue is empty, so shutdown cleanup removes the now-idle a. Nothing is left, so the executor is terminated.
  21. getState() returns ["EXECUTOR:TERMINATED"].


Please use Laptop/Desktop or any other large screen to add/edit code.