Forums Register Login

volatile mechanism in multithreading programming

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
Yes.

But this is too difficult a question for beginners. Moving.
+Pie Number of slices to send: Send
 

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:

+Pie Number of slices to send: Send
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
I don't get it. A whale wearing overalls? How does that even work? It's like a tiny ad wearing overalls.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1146 times.
Similar Threads
Which part of Java is sexy for you?
singleton,static,volatile in multithreaded
volatile?
static, instance methods, Thread safe issue
what is volatile
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 19:25:07.