0

Consider the following execution statements:

(1) Thread A: Checks for a specific lock state and fails (2) Thread A: Hence tries to go to wait state (3) Thread B : Done with a specific task and modified the lock state desired by Thread A (4) Thread B : Signals notifyAll()

Consider if Java's VM reorders the code to execute in the following order (1),(3),(4),(2). I believe such a condition is possible and in such a case, there might be an issue, because the Thread A goes to wait state forever as there is no other thread to notify!

EDIT 1: I am not using Synchronized block for the purpose of locking. Rather I am using AtomicInteger to gain a lock on a piece of code. Consider a RWLock Class and it has an atomic variable N. With the number of Readers and Writers coming in the lock state is incremented or decremented. The question is applicable to such a condition and not synchronized blocks/ methods.

New Coder
  • 499
  • 4
  • 22
  • That's why you need to hold the lock of an object to call wait or notify on it. That makes your sequence impossible. If I didn't understand correctly, then post code that illustrates your question. – JB Nizet Oct 05 '13 at 08:53
  • I have made some changes. If you need some more information please ask. – New Coder Oct 05 '13 at 19:03

1 Answers1

1

If you are using the wait()/notifyAll() pattern then you should be synchronizing on the lock object around both calls. This prevents the re-ordering you suggest.

For example

private final Object lock = new Object();

public void waiting()
{
  sychronized (lock)
  {
    while (waitCondition)
      lock.wait();
  }
}

public void notifying()
{
  sychronized (lock)
  {
    // change wait condition, probably

    lock.notifyAll();
  }
}
Mike Q
  • 22,839
  • 20
  • 87
  • 129
  • I am not using the synchronized blocks. I am using Atomic Integer to apply locks. Sorry, I should have specified that in my post. – New Coder Oct 05 '13 at 18:58