简体   繁体   中英

Java volatile variable, multi threading

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:

  • 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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM