Why are wait(), notify() and notifyAll() methods defined in the object class?

Ans: The purpose of the wait(), notify() and notifyAll() methods is to temporarily pause and resume the execution of code in an object. Typically the host object is not in a state where it can proceed with a method call it has been given and the thread of execution must literally wait for the object to return to a ready state. A common example would be a limited pool or store of objects where you must wait for a storage slot to be released or an object to be returned to the pool before you can use it.

public synchronized Object getNextObject() {

// Waiting loop
while (! objectAvailable()) {

try {

wait();
}
catch (InterruptedException e) {

// Handle exception
}
}

// No longer waiting, get the return object
Object returnObject;

// Assign the returnObject from store

// Notify state change for other waiters
notify();

return returnObject;
}
The act of waiting is associated with the Object class because any subclass may need to wait for a ready state to occur (Java is fundamentally a multi-threaded language). The waiting process acts on a single thread of execution, but the wait mechanism expects that multiple threads may be waiting for the same object. The wait() and notify() methods are hosted by the Object class so that the Java Virtual Machine can manage the “wait set” of threads through the objects they are waiting for.

People who read this post also read :



3 comments:

A Remarkable Relocation Guide Suitable For You

packers and movers pune
Welcome to here, a premium online tool helping consumers relocate from one place to another with household belongings or commercial commodities. We have made it easy to find right services, right moving companies and other related information in different major cities and towns of India packers and movers in pune.
movers and packers in pune

chung cư Eco Dream http://www.chungcu-ecodream.com/ cập nhật bảng giá mới nhất

Hi, great post! By the way, if perhaps you're looking for the best software developers in Poland, reach out to Pro4People - you'll find them right here. They did an amazing job for my business!

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More