wait(), notify() and notifyAll() in Java - A tutorial

By: Jagan Viewed: 224834 times  Printer Friendly Format    


The use of the implicit monitors in Java objects is powerful, but you can achieve a more subtle level of control through inter-process communication. As you will see, this is especially easy in Java.

Multithreading replaces event loop programming by dividing your tasks into discrete and logical units. Threads also provide a secondary benefit: they do away with polling. Polling is usually implemented by a loop that is used to check some condition repeatedly. Once the condition is true, appropriate action is taken. This wastes CPU time. For example, consider the classic queuing problem, where one thread is producing some data and another is consuming it. To make the problem more interesting, suppose that the producer has to wait until the consumer is finished before it generates more data. In a polling system, the consumer would waste many CPU cycles while it
waited for the producer to produce. Once the producer was finished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, and so on. Clearly, this situation is undesirable.

To avoid polling, Java includes an elegant interrocess communication mechanism via the wait( ), notify( ), and notifyAll( ) methods. These methods are implemented as final methods in Object, so all classes have them. All three methods can be called only from within a synchronized method. Although conceptually advanced from a computer science perspective, the rules for using these methods are actually quite simple:

  • wait( ) tells the calling thread to give up the monitor and go to sleep until some other
    thread enters the same monitor and calls notify( ).
  • notify( ) wakes up the first thread that called wait( ) on the same object.
  • notifyAll( ) wakes up all the threads that called wait( ) on the same object. The
    highest priority thread will run first.

These methods are declared within Object, as shown here:

final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )

Additional forms of wait( ) exist that allow you to specify a period of time to wait. The following sample program incorrectly implements a simple form of the producer/consumer problem. It consists of four classes: Q, the queue that you're trying to synchronize; Producer, the threaded object that is producing queue entries; Consumer, the threaded object that is consuming queue entries; and PC, the tiny class that creates the single Q, Producer, and Consumer.

// An incorrect implementation of a producer and consumer.
class Q {
int n;
synchronized int get() {
System.out.println("Got: " + n);
return n;
}
synchronized void put(int n) {
this.n = n;
System.out.println("Put: " + n);
}
}

class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}

class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}

class PC {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

Although the put( ) and get( ) methods on Q are synchronized, nothing stops the producer from overrunning the consumer, nor will anything stop the consumer from consuming the same queue value twice. Thus, you get the erroneous output shown here (the exact output will vary with processor speed and task load):

Put: 1
Got: 1
Got: 1
Got: 1
Got: 1
Got: 1
Put: 2
Put: 3
Put: 4
Put: 5
Put: 6
Put: 7
Got: 7

As you can see, after the producer put 1, the consumer started and got the same 1 five times in a row. Then, the producer resumed and produced 2 through 7 without letting the consumer have a chance to consume them.

The proper way to write this program in Java is to use wait( ) and notify( ) to signal in both directions, as shown here:

// A correct implementation of a producer and consumer.
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
if(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
if(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}

class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}

class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}

class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

Inside get( ), wait( ) is called. This causes its execution to suspend until the Producer notifies you that some data is ready. When this happens, execution inside get( ) resumes. After the data has been obtained, get( ) calls notify( ). This tells Producer that it is okay to put more data in the queue. Inside put( ), wait( ) suspends execution until the Consumer has removed the item from the queue. When execution resumes, the next item of data is put in the queue, and notify( ) is called. This tells the Consumer that it should now remove it.

Here is some output from this program, which shows the clean synchronous behavior:

Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5

This tutorial is an extract from the book "The complete Reference Java 2" by Herbert Schildt



Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. Thanks for the article. I got some clearance now.
View Tutorial          By: Reddy at 2008-03-15 00:02:17

2. nice article, many thanx :)
View Tutorial          By: Unknown at 2008-10-16 21:09:02

3. full copy of Java2 Complete Reference .

View Tutorial          By: power at 2008-12-01 06:12:23

4. very cool you said it! many thanks it's really coo
View Tutorial          By: ArAsh at 2008-12-11 06:41:13

5. thank you. it was very useful.
View Tutorial          By: ravindar at 2009-01-09 01:04:15

6. Great job!
Lot of things cleared...

View Tutorial          By: alok at 2009-03-18 10:45:25

7. i have clear that notify and wait
but where

View Tutorial          By: pp at 2009-06-29 06:12:13

8. notify does NOT wake up the first thread waiting.
View Tutorial          By: Armin at 2009-07-26 07:25:09

9. good example need some more explanation on notify
View Tutorial          By: prashant at 2009-09-08 19:29:54

10. Good example...easy to read and understand...
View Tutorial          By: Codventure at 2009-09-11 00:07:06

11. Its a nice article obviously. Can you put somethin
View Tutorial          By: kowser at 2009-10-06 23:44:52

12. Great article. The simple example used easily make
View Tutorial          By: Nikhil at 2009-11-13 08:38:41

13. Marvelous Explanation. The whole concept is clear
View Tutorial          By: Rohit at 2009-12-01 19:43:14

14. Excellent!!!!! Thanks
View Tutorial          By: nimbostratue at 2009-12-09 13:07:09

15. Good.understand
View Tutorial          By: Selva at 2009-12-29 23:27:29

16. Very nice and easy to understand, keep it up !!
View Tutorial          By: claudiu at 2010-02-07 06:12:30

17. is there a way to notify a specific thread?
View Tutorial          By: bob at 2010-03-23 11:57:29

18. Really a great article!
I have some questio

View Tutorial          By: ron at 2010-03-30 01:37:12

19. Very good. I like this way. First provide quite wr
View Tutorial          By: NJ at 2010-04-01 23:27:44

20. copy from Java Complete Reference 5th edition..
View Tutorial          By: nidhi at 2010-04-06 13:18:19

21. Very cool one, thanks, got the concept clear
View Tutorial          By: black boot at 2010-04-18 08:20:20

22. Does Wait() inside synchronized create a race cond
View Tutorial          By: Aviator168 at 2010-04-21 16:02:06

23. Does Wait() inside synchronized create a race cond
View Tutorial          By: Aviator168 at 2010-04-21 16:03:15

24. Nice article, Thank you
View Tutorial          By: kumar kasimala at 2010-04-26 21:09:25

25. Very nice article.. thanks
View Tutorial          By: Basu at 2010-05-29 05:52:00

26. I have one doubt regarding this code,
if th

View Tutorial          By: Yellappa at 2010-06-11 05:49:15

27. Hello,

your solution is kinda overk

View Tutorial          By: Hdm-Student at 2010-06-16 08:10:51

28. Just wanted to ask when the consumer is waiting fo
View Tutorial          By: Sanjeev at 2010-06-25 00:21:35

29. Explanations and examples are more clear. I like i
View Tutorial          By: Rajkumar S at 2010-07-12 22:28:40

30. 27: What happens if the producer and the customer
View Tutorial          By: Spender at 2010-07-25 14:42:08

31. Excellent Example to explain the functions
View Tutorial          By: manish at 2010-08-05 03:10:43

32. Thanks mate !!!

-- Anish Sneh

View Tutorial          By: Anish Sneh at 2010-08-18 07:42:56

33. really a nice article

thanks bro..

View Tutorial          By: irfan at 2010-10-01 06:22:57

34. @Hdm-Student THANK YOU!!! I didn't really get the
View Tutorial          By: metafa at 2010-10-14 08:39:24

35. nice!
View Tutorial          By: ol_beta at 2010-11-01 09:37:50

36. the code is wrong perhaps...i am very intelligent.
View Tutorial          By: sanik dutta at 2010-11-16 07:49:00

37. the code is wrong perhaps...i am very intelligent.
View Tutorial          By: sanik dutta at 2010-11-16 07:49:13

38. Why we need to override wait().notify() And notify
View Tutorial          By: chinmay at 2010-12-05 23:06:25

39. Thank you ... was very helpfull indeed !!
View Tutorial          By: Avinav at 2011-02-09 15:46:37

40. This program little hard to understand ..please gi
View Tutorial          By: sarav at 2011-02-17 05:02:46

41. Nice Article, but these concepts are pretty confus
View Tutorial          By: Goldest at 2011-03-18 01:50:50

42. nice article... got th topic clearly
View Tutorial          By: praba at 2011-05-09 23:29:26

43. how to send data one pc to another with java progr
View Tutorial          By: usman at 2011-05-14 01:31:31

44. Thanks alot. Really great and simple example!
View Tutorial          By: leo at 2011-06-06 13:58:32

45. Code indentation would help!...
View Tutorial          By: James at 2011-06-30 04:54:51

46. yes 29 you are correct! 27's example is prone to a
View Tutorial          By: sameendra at 2011-07-24 11:55:54

47. HixPexspeappy
View Tutorial          By: HixPexspeappy at 2011-08-01 19:20:39

48. why 27's example is prone to a deadlock ? when pro
View Tutorial          By: kaka at 2011-08-14 00:59:41

49. Thank you for such a article. It is extreamly nice
View Tutorial          By: Ravi at 2011-08-23 10:04:14

50. I could not understand, anyone having an easier ex
View Tutorial          By: aatish at 2011-09-14 09:52:28

51. I think 27's solution is OK, there is no deadlock
View Tutorial          By: xavier at 2011-09-22 05:09:58

52. Great job!! :)
View Tutorial          By: Desarrollo de software México at 2011-11-10 01:12:42

53. why r there these methods in Object class not in T
View Tutorial          By: santosh at 2011-11-16 06:58:06

54. look at this..
may help u...


View Tutorial          By: princess at 2011-11-30 12:06:22

55. this may help u..

class product

View Tutorial          By: princess at 2011-11-30 12:09:38

56. hope this may help u

class product<

View Tutorial          By: princess at 2011-11-30 12:11:57

57. I have a question. So here I have a progress bar,
View Tutorial          By: Nick at 2011-12-06 05:10:19

58. Nice article. Really helpful in understanding the
View Tutorial          By: Sundar at 2011-12-18 11:15:07

59. Excellent example Jagan. By the way I have a quest
View Tutorial          By: Shrihas at 2012-01-07 14:12:48

60. 29. It is not a deadlock. What will actually happe
View Tutorial          By: Sasha at 2012-01-24 14:34:03

61. Nice article. It explained me much !
View Tutorial          By: Przemo at 2012-04-05 10:28:32

62. Ditto.. its Complete Reference copy paste
View Tutorial          By: Sivasankar at 2012-06-07 10:18:55

63. Nice article .... Thank you...
View Tutorial          By: viswa at 2012-06-16 17:21:59

64. Hi,
Even if the while loops (in Producer an

View Tutorial          By: Pranay at 2012-09-19 19:08:45

65. Its Fully COPY from Herbert Schildt's Java Book...
View Tutorial          By: Sujay Mandal at 2012-10-08 16:28:35

66. Capoooooooooooooooooooo saludos desde Argentina Ju
View Tutorial          By: dengue8830 at 2012-10-14 02:42:09

67. Great Article...thanks :)
View Tutorial          By: Paras Chawla at 2012-10-28 04:35:57

68. Plagiarism!!!
CopyRight Infringement

View Tutorial          By: Tata McGraw Hill at 2012-11-03 15:42:40

69. clear concept explanation..
View Tutorial          By: ASHOK at 2013-01-16 07:31:35

70. Unfortunatelly this a BAD example of to communicat
View Tutorial          By: Mladen Covic at 2013-03-28 15:08:04

71. The complete, correct example can be found here:
View Tutorial          By: DCX at 2013-04-20 23:20:05

72. Dear !

Thanks for the article. Now

View Tutorial          By: Mubasher at 2013-05-04 11:37:52

73. nice one
View Tutorial          By: prashant at 2013-05-12 12:12:44

74. Many Thanks.
View Tutorial          By: Kallol Samaddar at 2013-07-11 18:26:06

75. Thanks lot tutor.
View Tutorial          By: veda murthy at 2013-08-01 09:33:43

76. Nice Example. Gives very clear idea.
View Tutorial          By: Larsen at 2013-09-14 02:29:24

77. Thank you!!!!!
View Tutorial          By: wsjonly at 2013-09-19 18:41:16

78. Thank you!!!!!
View Tutorial          By: wsjonly at 2013-09-19 18:41:50

79. it is possible to write any synchronisation progra
View Tutorial          By: shashi kant mishra at 2013-10-14 02:54:25

80. Hi ,

Since both the methods in the

View Tutorial          By: Chintan at 2013-11-21 03:42:32

81. You are using "this" to start to the thr
View Tutorial          By: sumit at 2014-10-30 08:14:55

82. its from complete reference page no-243
by

View Tutorial          By: maq webster at 2014-11-07 16:29:46

83. Good One..
View Tutorial          By: Subhranil Mukherjee at 2015-03-11 07:22:18

84. Thank you for your article.
View Tutorial          By: Jay at 2015-11-24 08:33:52

85. IT WAS HELPFUL......!!!!!!!
View Tutorial          By: SACHIN KOTHIWALE at 2016-09-12 09:21:47

86. Good One. Now I am clear about wait,notify and not
View Tutorial          By: Rajalingam at 2016-12-02 06:43:44

87. Good One. Now I am clear about wait,notify and not
View Tutorial          By: Rajalingam at 2016-12-02 06:44:17

88. Good One. Now I am clear about wait,notify and not
View Tutorial          By: Rajalingam at 2016-12-02 06:44:57

89. efitadquqone
View Tutorial          By: efitadquqone at 2017-01-03 19:12:43

90. ifetobaxacah
View Tutorial          By: ifetobaxacah at 2017-01-05 04:37:59

91. naziyixcap
View Tutorial          By: naziyixcap at 2017-01-06 02:52:13

92. ejuyewefujuis
View Tutorial          By: ejuyewefujuis at 2017-01-06 03:07:44

93. Cidessenak
View Tutorial          By: Cidessenak at 2017-01-29 20:16:00

94. Pres de lui, sur le canon d'arriere, etait pose un
View Tutorial          By: soin massage lyon at 2017-03-30 06:13:44

95. oqikekuqozige
View Tutorial          By: oqikekuqozige at 2017-04-01 13:21:27

96. adaacvuzvayo
View Tutorial          By: adaacvuzvayo at 2017-04-01 13:49:20

97. ubeteqejal
View Tutorial          By: ubeteqejal at 2017-04-01 15:25:28

98. Aseshimatsuh
View Tutorial          By: Adajidogek at 2017-04-09 15:23:23

99. Abukigewoj
View Tutorial          By: Amesenarig at 2017-04-13 16:43:56

100. Akigepeaz
View Tutorial          By: Azuyayusap at 2017-04-16 11:10:18

101. ______ ______!
View Tutorial          By: ______ ______ at 2017-04-19 18:20:33

102. Amizakuzoq
View Tutorial          By: Asewakapos at 2017-04-23 01:36:34

103. Abewopit
View Tutorial          By: Azutasoj at 2017-04-30 14:10:59

104. Akisapof
View Tutorial          By: Agebusuc at 2017-05-01 03:57:13

105. I see your website needs some unique content. Writ
View Tutorial          By: Freddygpzqzb at 2017-05-03 17:52:45

106. An awesome tip that no one has talked about but he
View Tutorial          By: simcity buildit game at 2017-05-03 19:47:33

107. Amoyapoa
View Tutorial          By: Asokinij at 2017-05-06 08:29:18

108. farmacia cialis
View Tutorial          By: farmacia cialis at 2017-05-08 07:21:11

109. Agirinax
View Tutorial          By: Akorehor at 2017-05-12 20:50:49

110. Yay google is my king helped me to find this outst
View Tutorial          By: push up bra best at 2017-06-01 16:17:17

111. ugulewoaluj
View Tutorial          By: ugulewoaluj at 2017-06-16 10:51:28

112. golewac
View Tutorial          By: golewac at 2017-06-16 11:08:35

113. igejvesokefi
View Tutorial          By: igejvesokefi at 2017-06-16 11:48:51

114. oyufuteyuje
View Tutorial          By: oyufuteyuje at 2017-06-17 01:05:11

115. evorajuj
View Tutorial          By: evorajuj at 2017-06-17 01:22:34

116. Eu alternei , certas coisas fechei com hospedaria
View Tutorial          By: site da Rio Promo at 2017-07-18 20:02:44

117. enamamamu
View Tutorial          By: enamamamu at 2017-07-29 03:27:32

118. izufuxaatiruk
View Tutorial          By: izufuxaatiruk at 2017-07-29 03:52:50

119. eticeziyo
View Tutorial          By: eticeziyo at 2017-07-29 04:21:26

120. azuzebilcekuq
View Tutorial          By: azuzebilcekuq at 2017-07-29 04:46:18

121. awudupqof
View Tutorial          By: awudupqof at 2017-07-29 07:13:57

122. All the java concepts clearly explained. Thanks fo
View Tutorial          By: priya at 2017-09-07 06:52:37

123. Howdy, I do think your blog could possibly be havi
View Tutorial          By: Www.H2Omwater.Com at 2017-09-10 12:06:04