• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread Synchronization block  RSS feed

 
William Cole
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all. I have 2 threads. The First one loops for 100 time before invoking anohter one.

Here's the code for 3 classes.







This works fine. However, when I change the synchronized block in MainCounter to cover more lines of code like this.



It looks like the ChildCounter is not invoked anymore (it is actually invoked unpredictably).

Could anyone explain what happened?
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are some simple rules that should be followed when using wait/notify:

  • You should never call wait() without confirming that you should indeed wait (check state in block while synchronized).
  • You should never assume that you are okay after returning from wait() (need to reconfirm state -- while synchronized).
  • You should never blindly notify waiting threads (check / set state for waiting threads -- while synchronized).


  • If you don't follow these rules, then you can get into situations where you are waiting when you shouldn't be, where you are senting notifications when you shouldn't be, or where you are sending notification where there is no thread waiting.

    It is this last case that is probably your issue. By extending your synchronized block to incorporate the delay loop, you give a better chance for the notifying thread to get the lock first. If that happens then the waiting thread will have to block at the sync lock grab -- and can't call wait. So... your notify thread sends the notification when the wait thread is not calling wait yet.

    Henry

     
    William Cole
    Greenhorn
    Posts: 2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Crystal clear. Thank you.

     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!