• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronized, wait, notify

 
Aaron Anders
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello folks, i'm confused with the relationship between synchronzied keyword and wait()/notify()/notifyall()...

does the internal implementation of synchronized method/statement make use of wait()/notify()/notifyall()?

i.e. does

same as

?
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Aaron Anders:
does the internal implementation of synchronized method/statement make use of wait()/notify()/notifyall()?
No. To the contrary, wait/notify are built upon the synchronized statement in the sense that you must own a monitor lock (i.e. be inside a synchronized method or block) before you can call wait() or notify() on an object.
Synchronization is a way to ensure that some operations are atomic w.r.t. other threads, in other words, that only one thread can execute the synchronized method(s) or block(s) at any given time. Inside a synchronized method/block, the thread is the exclusive owner of the object's monitor lock.
The wait/notify methods, on the other hand, are a way to co-ordinate actions between different threads. They allow a thread to release its monitor lock and wait() for something to happen, or to notify() waiting threads that something happened.
- Peter
 
Aaron Anders
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the reply.
i have one more question
while reading JDK doc, it says "wait() ... The current thread must own this object's monitor.", what will happen if i wait for object other than i've been synchronized for?
i.e.

just curious...
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It throws a ProgrammerFailedToReadAPIException.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic