Thread Safe Deferred Callback
Asynchronous programming involves being able to execute functions at a future occurrence of some event. Designing a thread-safe deferred callback class becomes a challenging interview question and we will learn about it in this lesson .
We'll cover the following...
Thread Safe Deferred Callback
Design and implement a thread-safe class that allows registeration of callback methods that are executed after a user specified time interval in seconds has elapsed.
Solution
Let us try to understand the problem without thinking about concurrency. Let's say our class exposes an API called registerAction()
that'll take a parameter action
, which will get executed after user specified seconds. Anyone calling this API should be able to specify after how many seconds should our class invoke the passed-in action.
One naive way to solve this problem is to have a busy thread that continuously loops over the list of actions and executes them as they become due. However, the challenge here is to design a solution that doesn't involve busy-waiting.
One possible solution is to have an execution thread that maintains a priority queue (min-heap) of actions ordered by the time remaining to execute each of the actions. The execution thread can sleep for the duration equal to the time duration before the earliest action in the min-heap becomes due for execution.
Consumer threads can come and add their desired actions in the min-heap within the critical section. The caveat here is that the execution thread will need to be woken up to recalculate the minimum duration it would sleep for before an action is due for execution. An action with an earlier due timestamp might have been added while the executor thread was sleeping on a duration calculated for an action due later than the one just added.
Consider this example: initially, the execution thread is sleeping for 30 mins before any action in the min-heap is due. A consumer thread comes along and adds an action to be ...