Asynchronous to Synchronous Problem
Explore how to make asynchronous executions synchronous in Java interview problems by extending classes and using wait() and notify() mechanisms. Understand signaling between threads and manage callbacks without modifying original source code.
We'll cover the following...
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 worktry {// Simulate useful work by sleeping for 5 secondsThread.sleep(5000);} catch (InterruptedException ie) {}callback.done();});t.start();}}
Callback Interface
public interface Callback {public void done();}
An example run would be as follows:
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 ...