0

code 1:

  class BCWCExamples  {
    public Object lock;

    boolean someCondition;

    public void NoChecking() throws InterruptedException {
        synchronized(lock) {
            //Defect due to not checking a wait condition at all
            lock.wait();  
        }
    }

code 2:

 public void IfCheck() throws InterruptedException {
            synchronized(lock) {
                // Defect due to not checking the wait condition with a loop. 
                // If the wait is woken up by a spurious wakeup, we may continue
                // without someCondition becoming true.
                if(!someCondition) { 
                    lock.wait();
                }
            }
        }

code 3:

public void OutsideLockLoop() throws InterruptedException {
            // Defect. It is possible for someCondition to become true after
            // the check but before acquiring the lock. This would cause this thread
            // to wait unnecessarily, potentially for quite a long time.
            while(!someCondition) {
                synchronized(lock) {
                    lock.wait();
                }
            }
        }

code 4:

public void Correct() throws InterruptedException {
            // Correct checking of the wait condition. The condition is checked
            // before waiting inside the locked region, and is rechecked after wait
            // returns.
            synchronized(lock) {
                while(!someCondition) {
                    lock.wait();
                }
            }
        }
    }    

Note:there is notify from some other place

there is no condition for wait in code 1 so infinite wait is there , but why the infinite wait is occurring in other 3 code(2,3,4)
kindly check the comments in the code for better understanding kindly help me out I am new in java wait and notify

1 Answers1

1

I your example I don't see any lock.notify() or lock.notifyAll() invocations.

Short and simple answer: You will wait() unlill you call notify() on the same object lock.

For additional inforamtion please consider looking into next links:

Community
  • 1
  • 1
ar4ers
  • 740
  • 5
  • 19