AlgoMaster Logo

Design Deferred Callback Executor

hard7 min readUpdated August 31, 2026
Listen to this chapter
Unlock Audio

Design a thread-safe executor that runs callbacks after their requested delays.

All delays are measured from the instant the DeferredExecutor is constructed. A task scheduled with delayMillis = 100 becomes eligible to run 100 milliseconds after construction, even if schedule itself is called later.

Implement these operations:

  • schedule(delayMillis, sequence, callback) adds a callback to the executor. Calls to schedule may happen concurrently.
  • runNext() waits for the earliest scheduled task to become due, invokes exactly that one callback, and then returns. If no task has been scheduled, it waits until one is available.

Tasks are ordered first by delayMillis, then by sequence. The judge uses distinct sequence values for tasks with the same delay.

The executor is single-threaded logically: even when several threads call runNext() concurrently, callbacks must never overlap. A callback must run outside the executor's internal lock, so it may safely schedule another task on the same executor.

If runNext() is waiting for a future task and another thread schedules a task with an earlier deadline, the waiting call must wake up and reconsider which task comes first. Waiting should use the language's blocking synchronization primitives rather than busy-waiting.

The judge creates the executor and all worker threads. Your implementation should provide only the synchronization inside DeferredExecutor.

The judge also preloads the standard concurrency, timing, callback, and collection APIs for each supported language. You do not need to add import, include, or using statements.

Example 1:

Input:

Output:

Explanation: The callback with the 10 millisecond delay becomes due before the callback with the 40 millisecond delay.

Example 2:

Input:

Output:

Explanation: Equal-delay tasks are ordered by their sequence values.

Constraints

  • 0 <= delayMillis <= 10_000
  • 0 <= sequence <= 1_000_000
  • At most 1_000 tasks are scheduled.
  • Sequence values are distinct among tasks with the same delay.
  • The same executor may receive concurrent calls to both methods.
  • Every runNext() call made by the judge eventually has a matching scheduled task.
  • Judge callbacks finish in finite time and do not throw exceptions.

Starter Code

Understanding the Problem

This executor combines three synchronization concerns:

  • Producers concurrently insert tasks into one ordered collection.
  • Consumers must sleep until work exists and until the earliest task is due.
  • Several consumer threads may call runNext, but the executor must invoke callbacks one at a time.

A thread cannot simply sleep for the first deadline it observes. While it sleeps, a producer may add an earlier task. The producer must notify the waiting thread, which then recomputes the earliest deadline.

The callback itself should not run while the queue lock is held. Doing that would block producers for the whole callback and deadlock a callback that calls schedule on the same executor.

Synchronization Strategy

Store tasks in a min-heap ordered by (deadline, sequence), where:

Protect the heap and a callbackRunning flag with one mutex. Use a condition variable, monitor, or wake-up channel to report any state change.

For schedule:

  1. Compute the deadline from the executor's shared start time.
  2. Acquire the mutex and push the task into the heap.
  3. Notify waiting runNext calls, because the new task may be the earliest one.

For runNext:

  1. Wait while another callback is running or the heap is empty.
  2. Examine the earliest task.
  3. If it is not due, perform a timed wait until its deadline. After any wake-up, loop and examine the heap again.
  4. Once the task is due, remove it and set callbackRunning while holding the mutex.
  5. Release the mutex and invoke the callback.
  6. Reacquire the mutex, clear callbackRunning, and notify other waiting calls.

The loop is essential: notifications, timeout wake-ups, and spurious wake-ups all require the condition to be checked again.

Correctness

All heap operations happen while holding the same mutex, so concurrent schedules and removals cannot corrupt the task collection.

runNext removes only the heap minimum and does so only after its deadline. Therefore, every executed task is due and no later task is selected while an earlier task remains queued. The heap's secondary key gives deterministic sequence order for equal delays.

Setting callbackRunning before releasing the mutex reserves the execution lane. Every other runNext waits until that flag is cleared, so callbacks cannot overlap. The selected task is removed exactly once before its callback runs, so two consumers cannot execute the same task.

Finally, schedule notifies waiters after every insertion. A consumer waiting for a later deadline wakes, checks the heap again, and adopts a newly inserted earlier deadline.

Code

Complexity Analysis

Let n be the number of queued tasks.

  • schedule: O(log n) time.
  • runNext: O(log n) heap-removal time, plus the required blocking delay and callback time.
  • Space complexity: O(n) for queued tasks and O(1) synchronization state.