The volatile keyword need to know

The role of 1.volatile keyword

  1) ensure visibility: I call the guarantee immediately visible, that is a different thread will get its new value immediately prior to use volatile variable modified, updated its latest value immediately after the modification.

  2) prohibit instruction reordering: JVM virtual machine allows the creation of addresses of variables, assignment, pointing to three operations to optimize the order, but this may cause errors in multithreaded scenarios, volatile prohibit such virtual machines at runtime optimization .

Whether it is safe 2.volatile

  Unsafe, although to ensure the visibility to ensure that the variable is updated immediately, but for non-atomic operations, such as i ++, is no guarantee that every step of the update immediately.

3.volatile when it is safe

  Read-only do not write, or write to ensure that only one thread

Guess you like

Origin www.cnblogs.com/yunqi0886/p/12408117.html