0 votes
in JAVA by
How do you call wait() method? using if block or loop? Why?

1 Answer

0 votes
by

wait() method should always be called in loop because it's possible that until thread gets CPU to start running again the condition might not hold, so it's always better to check condition in loop before proceeding. Here is the standard idiom of using wait and notify method in Java:

// The standard idiom for using the wait method

synchronized (obj) {

   while (condition does not hold)

      obj.wait(); // (Releases lock, and reacquires on wakeup)

      ... // Perform action appropriate to condition

}

See Effective Java Item 69 to learn more about why wait method should call in the loop.

Related questions

0 votes
asked Oct 26, 2023 in JavaScript by DavidAnderson
0 votes
asked Feb 12, 2020 in JAVA by rahuljain1
...