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?
Declaring a volatile Java variable means:
In other words, the main differences between synchronized and volatile are:
more information is: http://javamex.com/tutorials/synchronization_volatile.shtml
volatile is much simpler and faster than using synchronized.
As it is simpler it has limited uses, but if volatile is all you need, why use synchronized. ;)
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).
In short, we should use volatile
only at least when we have one variable (state) shared among threads. Less costlier than synchronized
, less intuitive
too. There are more than one variables holding the state volatile is a problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.