13.volatile synchronized compared with

synchronized, volatile memory are resolved visibility problem shared variable value, but the former is an exclusive lock, while only one thread calls the get () method, the other calling thread will be blocked, while there will be a thread context switching and thread reschedule overhead, and this is not good use of local lock mode. While the latter is non-blocking algorithms, it will not cause the overhead of thread context switching.

volatile visibility while providing guaranteed, but does not guarantee the atomicity operations.

When will generally use the volatile keyword it?

  • Writing does not depend on the value of the variable, the current value of the variable. Because if the current dependent value, is to obtain a three-step calculation of a write operation, the three steps of the operation are not atomic, volatile and does not guarantee atomicity.
  • Read variable value is not locked. Because the lock itself has to ensure the visibility of memory, this time do not need to declare a variable as volatile of.

Guess you like

Origin www.cnblogs.com/fly-book/p/11375244.html