...

/

Asynchronous to Synchronous Problem

Asynchronous to Synchronous Problem

A real-life interview question asking to convert asynchronous execution to synchronous execution.

Problem Statement

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(). In addition the method accepts a callback object which implements the Callback interface. the object’s done() gets invoked when the asynchronous execution is done. The definition for the involved classes is below:

Executor Class

public class Executor {

    public void asynchronousExecution(Callback callback) throws Exception {

        Thread t = new Thread(() -> {
            // Do some useful work
            try {
            // Simulate useful work by sleeping for 5 seconds
                Thread.sleep(5000);
            } catch (InterruptedException ie) {
            }
            callback.done();
        });
        t.start();
    }
}

Callback Interface

public interface Callback {

    public void done();
}

An example run would be as follows:

Press + to interact
class Demonstration {
public static void main( String args[] ) throws Exception{
Executor executor = new Executor();
executor.asynchronousExecution(() -> {
System.out.println("I am done");
});
System.out.println("main thread exiting...");
}
}
interface Callback {
public void done();
}
class Executor {
public void asynchronousExecution(Callback callback) throws Exception {
Thread t = new Thread(() -> {
// Do some useful work
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
callback.done();
});
t.start();
}
}

Note how the main thread exits before the asynchronous execution is completed.

Your task is to make the execution synchronous without changing the original classes (imagine, you are given the binaries and not the ...