Why must wait() always be in synchronized block

后端 未结 10 1118
傲寒
傲寒 2020-11-22 06:18

We all know that in order to invoke Object.wait(), this call must be placed in synchronized block, otherwise an IllegalMonitorStateException is thrown. But what\'s t

相关标签:
10条回答
  • 2020-11-22 07:11

    When you call notify() from an object t, java notifies a particular t.wait() method. But, how does java search and notify a particular wait method.

    java only looks into the synchronized block of code which was locked by object t. java cannot search the whole code to notify a particular t.wait().

    0 讨论(0)
  • 2020-11-22 07:12

    The problem it may cause if you do not synchronize before wait() is as follows:

    1. If the 1st thread goes into makeChangeOnX() and checks the while condition, and it is true (x.metCondition() returns false, means x.condition is false) so it will get inside it. Then just before the wait() method, another thread goes to setConditionToTrue() and sets the x.condition to true and notifyAll().
    2. Then only after that, the 1st thread will enter his wait() method (not affected by the notifyAll() that happened few moments before). In this case, the 1st thread will stay waiting for another thread to perform setConditionToTrue(), but that might not happen again.

    But if you put synchronized before the methods that change the object state, this will not happen.

    class A {
    
        private Object X;
    
        makeChangeOnX(){
            while (! x.getCondition()){
                wait();
                }
            // Do the change
        }
    
        setConditionToTrue(){
            x.condition = true; 
            notifyAll();
    
        }
        setConditionToFalse(){
            x.condition = false;
            notifyAll();
        }
        bool getCondition(){
            return x.condition;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 07:14

    What is the potential damage if it was possible to invoke wait() outside a synchronized block, retaining it's semantics - suspending the caller thread?

    Let's illustrate what issues we would run into if wait() could be called outside of a synchronized block with a concrete example.

    Suppose we were to implement a blocking queue (I know, there is already one in the API :)

    A first attempt (without synchronization) could look something along the lines below

    class BlockingQueue {
        Queue<String> buffer = new LinkedList<String>();
    
        public void give(String data) {
            buffer.add(data);
            notify();                   // Since someone may be waiting in take!
        }
    
        public String take() throws InterruptedException {
            while (buffer.isEmpty())    // don't use "if" due to spurious wakeups.
                wait();
            return buffer.remove();
        }
    }
    

    This is what could potentially happen:

    1. A consumer thread calls take() and sees that the buffer.isEmpty().

    2. Before the consumer thread goes on to call wait(), a producer thread comes along and invokes a full give(), that is, buffer.add(data); notify();

    3. The consumer thread will now call wait() (and miss the notify() that was just called).

    4. If unlucky, the producer thread won't produce more give() as a result of the fact that the consumer thread never wakes up, and we have a dead-lock.

    Once you understand the issue, the solution is obvious: Use synchronized to make sure notify is never called between isEmpty and wait.

    Without going into details: This synchronization issue is universal. As Michael Borgwardt points out, wait/notify is all about communication between threads, so you'll always end up with a race condition similar to the one described above. This is why the "only wait inside synchronized" rule is enforced.


    A paragraph from the link posted by @Willie summarizes it quite well:

    You need an absolute guarantee that the waiter and the notifier agree about the state of the predicate. The waiter checks the state of the predicate at some point slightly BEFORE it goes to sleep, but it depends for correctness on the predicate being true WHEN it goes to sleep. There's a period of vulnerability between those two events, which can break the program.

    The predicate that the producer and consumer need to agree upon is in the above example buffer.isEmpty(). And the agreement is resolved by ensuring that the wait and notify are performed in synchronized blocks.


    This post has been rewritten as an article here: Java: Why wait must be called in a synchronized block

    0 讨论(0)
  • 2020-11-22 07:14

    directly from this java oracle tutorial:

    When a thread invokes d.wait, it must own the intrinsic lock for d — otherwise an error is thrown. Invoking wait inside a synchronized method is a simple way to acquire the intrinsic lock.

    0 讨论(0)
提交回复
热议问题