educative.io

Can't we also use a semaphore to signal between methods?

We can make SyncExecutor as such:

class SyncExecutor extends Executor {

public void asynchronousExecution(Callback callback) throws Exception {
    Semaphore signal = new Semaphore(0);

    Callback cb = new Callback() {
        @Override
        public void done() {
            callback.done();
            signal.release();
        }
    };
    super.asynchronousExecution(cb);
    signal.acquire();
}

This prevents us from adding in hacky logic for isDone


Course: Java Multithreading for Senior Engineering Interviews - Learn Interactively
Lesson: Asynchronous to Synchronous Problem


Course: Java Multithreading for Senior Engineering Interviews - Learn Interactively
Lesson: Asynchronous to Synchronous Problem

Hi @Varun_Chitkara !!
Your suggestion to use a Semaphore in SyncExecutor is a great alternative, as demonstrated in your code:

class SyncExecutor extends Executor {
    public void asynchronousExecution(Callback callback) throws Exception {
        Semaphore signal = new Semaphore(0);

        Callback cb = new Callback() {
            @Override
            public void done() {
                callback.done();
                signal.release();
            }
        };
        super.asynchronousExecution(cb);
        signal.acquire();
    }
}

This approach indeed offers a cleaner and more direct way to handle synchronization, showcasing a good understanding of Java’s concurrency utilities.

However, the approach in our lesson, using wait() and notify() along with the isDone flag, serves a specific educational purpose:

class SynchronousExecutor extends Executor {
    @Override
    public void asynchronousExecution(Callback callback) throws Exception {
        Object signal = new Object();
        final boolean[] isDone = new boolean[1];
        Callback cb = new Callback() {
            @Override
            public void done() {
                callback.done();
                synchronized (signal) {
                    signal.notify();
                    isDone[0] = true;
                }
            }
        };
        super.asynchronousExecution(cb);
        synchronized (signal) {
            while (!isDone[0]) {
                signal.wait();
            }
        }
    }
}

This method is intended to provide deeper insights into the low-level workings of thread communication in Java. Understanding wait() and notify() is essential for comprehending the foundations upon which higher-level concurrency constructs like Semaphore are built. While your approach with Semaphore is more streamlined and practical for real-world applications, the lesson’s approach is designed to strengthen the foundational knowledge of Java’s concurrency mechanisms. Both methods are valuable, and understanding the underlying principles is key to becoming proficient in Java concurrency.
Happy Learning :blush: