Why is the wait() method always in the synchronized block?

Asked 1 years ago, Updated 1 years ago, 144 views

Object.Everyone knows that the method must be in the synchronized block to generate the wait()method. Otherwise, IllegalMonitorStateException will occur. Why are these restrictions? I know that the wait() method releases the monitor, but why do I have to explicitly obtain the monitor by calling the wait() method after creating a synchronized block?

What is the potential risk of delaying the call thread if wait() is executed outside the synchronization block, that is, while maintaining meaning?

multithreading java wait concurrency

2022-09-21 18:25

1 Answers

Wait() is a meaningful method when the notify() method also exists. So it's always about interaction between threads, and you need synchronization to work. You may think that these processes should be implicit, but they are not helpful at all for the following reasons::

It's not always wait() in meaning. There is a condition to be satisfied, otherwise wait until it is satisfied. It's going to work like this.

if(!condition){
    wait();
}

However, if condition is set by multiple threads, synchronization is required for proper operation.

There are a few more things that are wrong because the thread stops waiting does not necessarily mean that condition is true:

What is needed to solve these cases is to modify the code below always:

synchronized(lock){
    while(!condition){
        lock.wait();
    }
}

It would be better to solve the concepts provided by the java.util.concurrent package without being bound by Synchronization.


2022-09-21 18:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.