Java Concurrency : Synchronized(this) => and this.wait() and this.notify()
I would appreciate your help in understanding a "Concurrency Example" from: http://forums.sun.com/thread.jspa?threadID=735386
public synchronized void enqueue(T obj) { // do addition to internal list and then... this.notify(); } public synchronized T dequeue() { while (this.size()==0) { this.wait(); } return // something from the queue }
My Question is: Why is this code valid?
=> When I synchronize a method like "public synchronized
" => then I synchronize on the "Instance of the Object ==> this
".
However in the example above:
Calling "dequeue" I will get the "lock/monitor" on
this
Now I am in the dequeue method. As the list is zero, the calling thread will be "
waited
"From my understanding I have now a deadlock situation, as I will have no chance of ever enqueuing an object (from another thread), as the "dequeue" method is not yet finished and the dequeue "method" holds the lock on
this
: So I will never ever get the possibility to call "enqueue" as I will not get the "this
" lock.
Background: I have exactly the same problem: I hav开发者_开发问答e some kind of connection pool (List of Connections) and need to block if all connections are checked. What is the correct way to synchronize the List to block, if size exceeds a limit or is zero?
See: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait()
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the
notify
method or thenotifyAll
method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
So no, there is no deadlock. When wait()
is called, the monitor held by the thread is released, allowing enqueue (and other operations that are synchronized on this
object) to be called on another thread. When the thread is notified, it will try to obtain the monitor again before continuing.
There is no deadlock cause calling wait will give up the lock. you might check this out: Why must wait() always be in synchronized block
精彩评论