7

Consider the following code :-

class CalculateSeries implements Runnable{
    int total;
    public void run(){
        synchronized(this){                          // *LINE 1* 
            for(int i = 1; i <= 10000; i++) {
                total += i;
            }

            notify(); //Notify all the threads waiting on this instance of the class to wake up
        }
    }
} 

Another class is waiting on an instance of this class by getting the lock on it inside a synchronized block. But if I don't keep the code in run method in a synchronized block, then I get IllegalMonitorStateException.

notify() should mean to give signal to all the threads waiting. Then why should it be inside synchronized block?

adarshr
  • 61,315
  • 23
  • 138
  • 167
whitehat
  • 2,381
  • 8
  • 34
  • 47

2 Answers2

5

notify() should mean to give signal to all the threads waiting.

Actually, no. It signals one arbitrarily chosen waiting thread. notifyAll() signals all of them.

Then why should it be inside synchronized block?

Because waiting doesn't happen for its own sake. You check for a condition and if it's not met, you wait until someone tells you it may now be met (then you check again). Without synchronization, you would have race conditions between checking the condition and actually waiting.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
  • 6
    This explains why `wait()` must be inside `synchronized`, but not `notify()`. Note that, for example, [in the C++ API, this is explicitly discouraged](http://en.cppreference.com/w/cpp/thread/condition_variable/notify_one). So it leaves open the question of why Java requires it. – Owen Oct 08 '16 at 00:13
  • @P.Soutzikevich: Both your statements are wrong. Concurrency was one of the main design and selling points of Java back then (see the third bullet point in the original 1996 whitepaper here: https://www.oracle.com/technetwork/java/intro-141743.html#318) However, its *approach* to concurrency was definitely not visionary, just an incremental improvement over C/C++. Despite this, Java most definitely is one of the go-to languages for certain kinds of highly parallelized or concurrent applications. Hadoop, Akka, Kafka, ever heard of those? – Michael Borgwardt Jun 03 '19 at 20:12
0

if notify() method is not within synchronized block then it would be useless to place wait() into synchronized block.
Take scenario of producer-consumer model, producer and consumer both the methods will execute concurrently because one of them is not synchronized. There will be a race condition.

Arun Raaj
  • 1,762
  • 1
  • 21
  • 20