【Transfer】The difference between volatile and synchronized

The difference between volatile and synchronized

  1. The essence of volatile is to tell the jvm that the value of the current variable in the register (working memory) is uncertain and needs to be read from the main memory; synchronized locks the current variable, only the current thread can access the variable, and other threads are blocked. .
  2. volatile can only be used at the variable level; synchronized can be used at the variable, method, and class level
  3. Volatile can only achieve the modification visibility of variables, and cannot guarantee atomicity; while synchronized can guarantee the modification visibility and atomicity of variables
  4. Volatile will not cause thread blocking; synchronized may cause thread blocking.
  5. Variables marked with volatile will not be optimized by the compiler; variables marked with synchronized can be optimized by the compiler

http://blog.csdn.net/suifeng3051/article/details/52611233

JMM:  http://blog.csdn.net/suifeng3051/article/details/52611310

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326833648&siteId=291194637