aspose file tools
The moose likes Threads and Synchronization and the fly likes volatile mechanism in multithreading programming Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "volatile mechanism in multithreading programming" Watch "volatile mechanism in multithreading programming" New topic
Author

volatile mechanism in multithreading programming

Raj chiru
Ranch Hand

Joined: Aug 12, 2008
Posts: 140
Hi...
volatile mechanism wil be used in multithreading programming,but my dout is
Can I only use the volatile mechanism in the absence of synchronization mechanism?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32712
    
    4
Yes.

But this is too difficult a question for beginners. Moving.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 3041
    
    4

raj chiru wrote:Hi...
volatile mechanism wil be used in multithreading programming,but my dout is
Can I only use the volatile mechanism in the absence of synchronization mechanism?



If I understand the question, then it is "Can I use volatile only without using synchronization (rather than using volatile with synchronization)". The answer to that is No. See below.
If the question actually is "Is volatile the only way to have thread-safe values that can be updated and reflected safely in all Threads without using synchronization", then the answer is Yes (assuming you take the java.util.concurrent Locks as being an extension of synchronization).

You can use volatile in the absence of synchronization to report state in a thread safe manner - for example to make sure the most 'up to date' value for a variable is available to all threads.

You can use volatile in conjunction with synchronization, and may need to if you link the value that should be reported to its current state. For example:

May not be thread safe (if multiple threads call this increment code). The increment is not an atomic command (it takes 2 commands to perform) so if 2 threads try to increment the counter at the same time, then the counter value may be invalid. In this case you would have to do:


Steve
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16695
    
  19

Also note... that using volatile by itself is very simplistic. You can't really do much with it. If you want to do complex operations without any synchronization, you can look into using the classes in the java.util.concurrent.atomic package.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: volatile mechanism in multithreading programming
 
Similar Threads
singleton,static,volatile in multithreaded
static, instance methods, Thread safe issue
Which part of Java is sexy for you?
what is volatile
volatile?