Why wait and notify called from a synchronized method in Java?

By | March 7, 2023

In Java, wait() and notify() are methods that are used for inter-thread communication, specifically for thread synchronization. When wait() is called, the current thread is suspended and waits for another thread to notify it. When notify() is called, it wakes up one of the threads that are waiting for the same object’s monitor.

wait() and notify() should always be called from a synchronized block or method. This is because they require a lock on the object’s monitor, and if the lock is not held, an IllegalMonitorStateException will be thrown.

Additionally, synchronization ensures that the changes made by one thread are visible to all other threads, which is necessary for the correct functioning of wait and notify.

Here is an example to demonstrate the usage of wait and notify:

class Message {
private String message;
private boolean empty = true;

public synchronized String read() {
while(empty) {
try {
wait();
} catch (InterruptedException e) {}
}
empty = true;
notifyAll();
return message;
}
public synchronized void write(String message) {
while(!empty) {
try {
wait();
} catch (InterruptedException e) {}
}
empty = false;
this.message = message;
notifyAll();
}
}

class Reader implements Runnable {
private Message message;

public Reader(Message message) {
this.message = message;
}

public void run() {
String msg;
while((msg = message.read()) != null) {
System.out.println(msg);
}
}
}

class Writer implements Runnable {
private Message message;

public Writer(Message message) {
this.message = message;
}

public void run() {
String[] messages = {“Hello”, “World”, “Goodbye”};
for(String message : messages) {
this.message.write(message);
}
this.message.write(null);
}
}

public class Main {
public static void main(String[] args) {
Message message = new Message();
new Thread(new Reader(message)).start();
new Thread(new Writer(message)).start();
}
}

In this example, the Message class represents a shared message that can be read and written by multiple threads. The read() and write() methods are synchronized, and they use wait() and notifyAll() to suspend and wake up threads that are waiting for the message.

The Reader and Writer classes are two threads that read and write to the message, respectively. The Main class starts the threads and runs the program.

In summary, wait() and notify() are used for thread synchronization, and they should be called from a synchronized block or method to ensure proper synchronization and avoid IllegalMonitorStateException.

 

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *