Java Concurrency : Synchronized(this) => and this.wait() and this.notify()

Posted by jens on Stack Overflow See other posts from Stack Overflow or by jens
Published on 2010-05-19T04:18:59Z Indexed on 2010/05/19 4:30 UTC
Read the original article Hit count: 413

Filed under:
|

Hello Experts,

I would appreciate your help in understand a "Concurrency Example" from: http://forums.sun.com/thread.jspa?threadID=735386

Qute Start:

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
}

Quote End:

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:

  1. Calling "dequeue" I will get the "lock/monitor" on this

  2. Now I am in the dequeue method. As the list is zero, the calling thread will be "waited"

  3. From my understanding I have now a deadlock situation, as I will have no chance of ever enquing an object (from an nother thread), as the "dequeue" method is not yet finised and the dequeue "method" holds the lock on this: So I will never ever get the possibility to call "enequeue" as I will not get the "this" lock.

Backround: I have exactly the same problem: I have 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?

Thank you very much

Jens

© Stack Overflow or respective owner

Related posts about java

Related posts about concurrency