user6454491
user6454491

Reputation: 158

Deadlock behaviour having 3 threads with wait and notify

I have 3 Threads, all 3 doing the same thing "[...]" (e.g. writing to a list, on which we synchronize):

public void run(){
  long time= System.currentTimeMillis();
  while(System.currentTimeMillis - time < 10000){
    synchronized(object){
      [...]
      object.notifyAll();
      object.wait();
    }
  }
  System.out.println(Thread.currentThread.getName() + " just finished");
}

What I found curious, is that when one thread exits the while-loop, a deadlock occurs. My problem is not that it happened, as it is exactly what I was testing, but when it occured. Shouldn't the deadlock happen after two threads are finished because there is one left that cannot be notified by any of the finished two?
Of course there is a chance that two threads call their "wait" at the same time, so we get a deadlock after just one finished thread because the two waiting ones cannot be woken up by the finished one, but I have run the test numerous times and the result is always the same: Deadlock after just one finished thread.

Am I missing something?

Upvotes: 0

Views: 141

Answers (1)

David Schwartz
David Schwartz

Reputation: 182819

The wait function will wait whether there's something to wait for or not. Before you call wait, you must check whether the thing you want to wait for has already happened -- that's why you're in a synchronized block, so that you hold the lock that protects the shared state that you are waiting for.

You will never get wait/notifyAll to work without some shared state that you are waiting to reach some particular state. You must use the lock to protect that shared state, and you must check its state before calling wait. Otherwise, you will always have possible races including the one you are seeing where you wait for something to happen even though it has already happened, thus waiting forever.

Upvotes: 1

Related Questions