File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Volatile use with Synchronization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Volatile use with Synchronization" Watch "Volatile use with Synchronization" New topic

Volatile use with Synchronization

Thakur Sachin Singh
Ranch Hand

Joined: Jun 15, 2010
Posts: 238

i am running below code using volatile keyword but it gives result unexpected. it is working on two threads but not with the three.

if i am using two thread then it give output something like this:
Thread 1 : 1
Thread 2 : 1
Thread 1 : 2
Thread 2 : 2
Thread 1 : 3
Thread 2 : 3
Thread 1 : 4
Thread 2 : 4
Thread 1 : 5
Thread 2 : 5

please tell me why this is not working in three thread?

SCJP 6- 91%, IBM DB2, IBM RAD Certified
Jelle Klap

Joined: Mar 10, 2008
Posts: 1950

You should always wait() in a loop that test's if the wait condition is satisfied.
The two thread version is equally broken, by the way, because a thread can also wake up without being notified, which is called spurious wakeup.

Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Thakur Sachin Singh
Ranch Hand

Joined: Jun 15, 2010
Posts: 238

can you tell me from some other way
I agree. Here's the link:
subject: Volatile use with Synchronization
jQuery in Action, 3rd edition