Is the call position notify ()? (Java)

Suppose I have the following situation:

synchronized void someMethod() { ... try { wait(); }catch(InterruptedException e) { System.out.println("InterruptedException caught"); } ... } 

and

 synchronized void someOtherMethod() { ... notify(); } 

And Thread calls the first someMethod , goes to wait , and then someOtherMethod notifies it and returns to Runnable state. Does the position of the notify() call in the method mean? I did not notice a change in behavior, even when I positioned the call to notify() in different positions inside the method.

Should Thread notify immediately after calling notify() ?

+4
source share
3 answers

The position of the notify() call in the synchronized block does not matter, because by definition, if you are still in the synchronized block, you still hold the lock.

Should you notify the thread immediately when calling notification ()?

Yes. The notify() call puts one of the threads (if any) from the wait queue (waiting for the condition) to the blocked queue (waiting for the lock). This happens immediately, but the awakened thread must get a lock before it starts working. Therefore, it immediately moves out of the waiting queue, but is still waiting to receive a lock.

Btw, I would recommend writing this as this.wait() and this.notify() to be explicit about which object is affected.

+5
source

No, the position of the notify () call inside the synchronized block does not matter.

I recommend the style:

 class SomeClass { synchronized void someMethod() throws InterruptedException{ ... while (! someCondition) { wait(); } ... } synchronized void someOtherMethod() { ... makeConditionValid(); notifyAll(); } } 

Note the use of the while around the wait call. Some JVMs may issue false notifications, so there is no guarantee that when a thread is notified, the original condition that caused it to wait is valid. In addition, the awakened thread does not start until the notification thread releases the lock; therefore, it is possible that by the time the waiting thread has met the condition, this is again invalid.

+2
source

These calls (i.e., Object#wait and Object#notify ) must be executed in a synchronized block. Since your method is synchronized, the scope of the synchronized block includes all the functions inside the method. Therefore, positioning has nothing to do with it.

0
source

All Articles