educative.io

Was the requirements to use wait and notify?

I am wondering whether there were requirements to use notify and wait methods or if you can use other things like volatile to achieve the same result. Was there anything like that?


Course: https://www.educative.io/courses/java-multithreading-for-senior-engineering-interviews
Lesson: Asynchronous to Synchronous Problem

Hello @Pavel_Shchahelski
The specific requirement to use notify() and wait() methods was mentioned in the provided solution. As you mentioned, alternative ways exist to achieve synchronization between threads without explicitly using wait() and notify() methods. The use of volatile keyword in Java can also ensure the visibility of changes made by one thread to other threads.

Here’s how you can modify the solution to use volatile:

public class SynchronousExecutor extends Executor {

    @Override
    public void asynchronousExecution(Callback callback) throws Exception {
        final volatile boolean[] isDone = new boolean[1];
        Callback cb = new Callback() {
            @Override
            public void done() {
                callback.done();
                isDone[0] = true;
            }
        };
        super.asynchronousExecution(cb);
        while (!isDone[0]) {
            // Busy waiting until isDone is true
        }
    }
}

By declaring the isDone array as volatile, you ensure that changes made to this variable in one thread are visible to other threads. However, note that this approach relies on busy waiting (while (!isDone[0])) which can be resource-intensive. It continuously checks the value of isDone until it becomes true.

Using volatile here eliminates the need for explicit synchronization constructs like wait() and notify(). However, in practice, busy waiting might not be an efficient solution, especially when dealing with complex applications or cases where the waiting time could be longer.

I hope this will help.
Happy learning!