Comment on Tutorial - wait(), notify() and notifyAll() in Java - A tutorial By Jagan



Comment Added by : Mladen Covic

Comment Added at : 2013-03-28 15:08:04

Comment on Tutorial : wait(), notify() and notifyAll() in Java - A tutorial By Jagan
Unfortunatelly this a BAD example of to communicate between Threads. In general, it is a bad idea to use wait and notify to communicate between Threads ONLY relying on wait and notify. The reason is very simple: nothing guaranties that object waiting will receive the proper notification. In other words it might either :

A) receive notification sent from someone else and NOT Producer.

just add this in main method at the end
synchronized(q)
{
q.notify();
}

or

B) Consumer never receives the notification and hangs

just add in the main method:

synchonized(q)
{
...
// do something forever without releasing the lock on q
}

In general, communication between threads should be done either through Events and (synchronized) EventMulticasters or anchored around VERY protected (encapsulated) synchronized object with with wait and notify only called on that object. Even then there is a pssibkity of messing that object's monitor.


View Tutorial



Subscribe to Tutorials

Related Tutorials

Program using concept of byte long short and int in java

Update contents of a file within a jar file

Tomcat and httpd configured in port 8080 and 80

Java File

Java String

Count number of vowels, consonants and digits in a String in Java

Reverse a number in Java

Student marks calculation program in Java

Handling Fractions in Java

Calculate gross salary in Java

Calculate average sale of the week in Java

Vector in Java - Sample Program

MultiLevel Inheritance sample in Java

Multiple Inheritance sample in Java

Java program using Method Overriding

Archived Comments

1. we want to learn j2me
View Tutorial          By: vijay at 2010-09-27 02:34:59

2. this code works very well for me , but it runs onl
View Tutorial          By: m. usman at 2013-08-31 14:17:22

3. When I use this code it puts everything I append o
View Tutorial          By: Amber at 2012-06-18 15:33:22

4. Hi,

Your COM port is currently in u

View Tutorial          By: Ramlak at 2008-04-14 07:29:55

5. can any one share the link for downloading the fir
View Tutorial          By: jay at 2012-01-17 14:21:28

6. The above code works for me. When I run the progra
View Tutorial          By: Avinash at 2011-12-01 10:20:19

7. Dear Samantha, Thx for pointing the extra \. I hav
View Tutorial          By: Emiley at 2011-06-06 04:50:40

8. Good one.....
View Tutorial          By: Ratnam.. at 2012-07-03 07:11:26

9. good one nice
View Tutorial          By: megha at 2011-07-16 15:54:29

10. Sir, I need to use MS Access as a database in java
View Tutorial          By: John Moses at 2012-03-31 00:20:38