This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
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 Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Volatile use with Synchronization" Watch "Volatile use with Synchronization" New topic
Author

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
............more

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




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

Joined: Mar 10, 2008
Posts: 1924
    
    7

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’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: Volatile use with Synchronization
 
It's not a secret anymore!