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.
We'll cover the following...
Problem Statement
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 registerCallback()
that'll take a parameter of type Callback
, which we'll define later. Anyone calling this API should be able to specify after how many seconds should our executor invoke the passed in callback.
One naive way to solve this problem is to have a busy thread that continuously loops over the list of callbacks and executes them as they become due. However, ...