Asynchronous to Synchronous Problem
A real-life interview question asking to convert asynchronous execution to synchronous execution.
Asynchronous to Synchronous Problem
This is an actual interview question asked at Netflix.
Imagine we have an Executor
class that performs some useful task asynchronously via the method asynchronousExecution()
. Additionally, the method accepts a callback object which implements the Callback
interface. The passed-in callback object’s done()
method gets invoked when the asynchronous execution is complete. The definition for the involved classes is below:
Press + to interact
public class Executor{public void asynchronousExecution(Callback callback){Thread t = new Thread(() =>{// Simulate useful work by sleeping for 5 secondsThread.Sleep(5000);callback.done();});t.Start();}}
Callback Interface and Implementation
Press + to interact
public interface ICallback{void done();}public class Callback : Callback{public void done(){Console.WriteLine("I am done");}}
An example run would be as follows:
Press + to interact
using System;using System.Threading;class Demonstration{static void Main(){Executor executor = new Executor();executor.asynchronousExecution(new Callback());Console.WriteLine("main thread exiting...");}}public interface ICallback{void done();}public class Callback : ICallback{public void done(){Console.WriteLine("I am done");}}public class Executor{public void asynchronousExecution(ICallback callback){Thread t = new Thread(() =>{// Simulate useful work by sleeping for 5 secondsThread.Sleep(5000);callback.done();});t.Start();}}
Note, the main thread exits before the asynchronous execution is completed. The print-statement from the main thread prints before the print-statement from the ...