1

In Java, is it required to use thread wait() and notify() within a synchronized block?

user207421
  • 305,947
  • 44
  • 307
  • 483
DeadManSpirit
  • 2,036
  • 2
  • 20
  • 27
  • 3
    This question is confusing because if you are going to use wait() it must be inside a synchronized block, but if you are going to use a synchronized block it is not mandatory to have a wait/notify, which situation is the one you are asking about? – ilcavero Feb 13 '13 at 23:14
  • 1
    When the threads need to pass data around, it’s not enough to say “don’t run on the same data while I am running” but each thread must tell another thread that “I have some data for you”. In this case we require thread wait and notify. So synchronized behavior is different from wain/notify – DeadManSpirit Feb 13 '13 at 23:17

2 Answers2

4

No. Java will automatically ensure the marked section is entered by one and only one thread.

http://tutorials.jenkov.com/java-concurrency/synchronized.html

see also this question: java: wait(), notify() and synchronized blocks


Hmm.. seems to be some language issues.

You are not required to use wait and notify in a synchronized block, but if you want to use wait and notify, they must be used within a synchronized block.

Community
  • 1
  • 1
PaulProgrammer
  • 16,175
  • 4
  • 39
  • 56
2

in short, yes. The thread must own the object's monitor before calling wait or notify.

Community
  • 1
  • 1
Ralf H
  • 1,392
  • 1
  • 9
  • 17