• Post Reply Bookmark Topic Watch Topic
  • New Topic

volatile mechanism in multithreading programming

 
Raj chiru
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Posts: 52581
119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.

But this is too difficult a question for beginners. Moving.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

 
Henry Wong
author
Sheriff
Posts: 22532
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!