...

/

Thread Safe Deferred Callback

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.

Thread Safe Deferred Callback

Design and implement a thread-safe class that allows registration 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 addAction() 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 our class should 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 which doesn't involve a busy thread.

One possible solution is to have an execution thread that maintains a ...

Access this course and 1400+ top-rated courses and projects.