Junior — Middle
What is the main purpose of the notify() method in the Object database in Java?
sobes.tech AI
Answer from AI
The notify() method in Java is called on an object to wake up one of the threads that are waiting on that object (i.e., have called wait()). It is part of the thread synchronization mechanism.
When a thread calls wait() on an object, it releases the object's monitor and enters a waiting state. The notify() method wakes up one of these waiting threads, allowing it to continue execution after it re-acquires the monitor.
Example:
synchronized(obj) {
obj.notify(); // wakes up one thread waiting on obj
}
Important: notify() must be called within a block synchronized on the same object, otherwise an exception will be thrown.