I have an application which are multi threading. I notice some existing code use volatile when the variable is shared by several threads. Why not just use synchronized in the method when variable is used, what's the benefits to define variable as volatile?
-
3out of top of my head - don't touch it, if you don't understand how it worksBoris Treukhov– Boris Treukhov2012-02-14 10:34:12 +00:00Commented Feb 14, 2012 at 10:34
-
2there are dozens of web page explaining thisGuillaume Polet– Guillaume Polet2012-02-14 10:36:46 +00:00Commented Feb 14, 2012 at 10:36
-
1search the web for "Java Memory Model"Miquel– Miquel2012-02-14 10:39:51 +00:00Commented Feb 14, 2012 at 10:39
-
maybe the authours struggle for scalability, maybe they implement en.wikipedia.org/wiki/Double-checked_locking, maybe they don't want to share the implicit Object locks or to allocate explicit monitor objects, maybe they implement some non blocking algorithm, maybe ..Boris Treukhov– Boris Treukhov2012-02-14 10:49:56 +00:00Commented Feb 14, 2012 at 10:49
4 Answers
Declaring a volatile Java variable means:
- The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory";
- Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.
In other words, the main differences between synchronized and volatile are:
- a primitive variable may be declared volatile (whereas you can't synchronize on a primitive with synchronized);
- an access to a volatile variable never has the potential to block: we're only ever doing a simple read or write, so unlike a synchronized block we will never hold on to any lock;
- because accessing a volatile variable never holds a lock, it is not suitable for cases where we want to read-update-write as an atomic operation (unless we're prepared to "miss an update");
- a volatile variable that is an object reference may be null (because you're effectively synchronizing on the reference, not the actual object).
more information is: http://javamex.com/tutorials/synchronization_volatile.shtml
Comments
Taken from here:
A primitive variable may be declared volatile (whereas you can't synchronize on a primitive with synchronized);
An access to a volatile variable never has the potential to block: we're only ever doing a simple read or write, so unlike a synchronized block we will never hold on to any lock;
Because accessing a volatile variable never holds a lock, it is not suitable for cases where we want to read-update-write as an atomic operation (unless we're prepared to "miss an update");
A volatile variable that is an object reference may be null (because you're effectively synchronizing on the reference, not the actual object).