2

I've started investigating multithreading more deeply and I'm not quite sure I understand why do I need to add synchronized keyword if I use wait/notify mechanism. Can someone please explain it a bit?

Alex
  • 1,940
  • 2
  • 18
  • 36

1 Answers1

1

For example, one thread read data from a buffer and one thread write data into buffer. The reading data thread needs to wait until the writing data thread completly write a block data into the buffer. The wirting data thread needs to wait until the reading data thread completly read the data from the buffer. If wait() and notify()methods can be called by a ordinary method , the reading thread calls wait() and the thread is being added to waiting queue. At just the same moment, the writing thread calls notify() to signal the condition changes. The reading thread misses the change and waits forever. So due to race condition here we potential lost a notification and if we use buffer or just one thread will be waiting forever and program will hang. Since the wait() method in Java also releases the lock prior to waiting and reacquires the lock prior to returning from the wait() method, we must use this lock to ensure that checking the condition (buffer is full or not) and setting the condition (taking element from buffer) is atomic which can be achieved by using synchronized method or block in Java.. Hence, they must be called inside a synchronized method or block which is mutually exclusive(mutex).

Neeraj Yadav
  • 422
  • 6
  • 13
  • Thanks for you answer. Can you please explain more what is the waiting queue? Are there any order in releasing the lock if for example several threads call wait on the same object – Alex Dec 14 '17 at 21:51
  • If you are quoting some article at least point the source, like: http://www.xyzws.com/javafaq/why-wait-notify-notifyall-must-be-called-inside-a-synchronized-method-block/127 – Pshemo Dec 14 '17 at 21:56