Two JAVA memory model (JMM)

  • JMM introduction:

      The java memory model is an abstract concept and does not really exist. The specified variables are stored in the main memory, which is a shared area that can be accessed by all threads. But the operation of the variable must be completed in the working memory (the working memory is a private data area created by the JVM for each thread), first copy the variable from the main memory to its own working memory, and then operate on the variable, the operation is completed and written back to the main RAM.

  • Three characteristics:

      1. Visibility: 多个线程操作共享数据彼此可见;
      2 atomic: 操作是连续不可分割;
      3 ordering: 计算机执行程序为了提高性能,编译器和处理器常常会对指令重排,分三种:1、编译器优化的重排;2、指令并行的重排;3、内存系统的重排,它们需要数据的依赖性来保证最终结果一致,可以禁止指令重排;

Volatile

  It is a lightweight lock that can guarantee memory visibility and order (instruction reordering is prohibited), and does not guarantee atomicity. Use scenarios such as: local program cache synchronization, the flag to determine whether it is being synchronized can be modified with volatile.

AtomicInteger或AtomicReference

  Atomicity can be achieved, the underlying CAS algorithm. The algorithm has three values: 1. memory value; 2. estimated value; 3. updated value; only when the memory value is equal to the estimated value, the updated value will be assigned to the memory value, otherwise spin.image.png

The full name of CAS is Compare And Swap, which is a CPU concurrent original statement that is not allowed to be interrupted during execution.

The CAS core class is the UnSafe class. All methods in this class are natively modified and can directly manipulate specific memory data.

Disadvantages of CAS: long cycle time will be very expensive; only atomic operations of a shared variable can be guaranteed; there are ABA problems. ABA problems such as: thread one takes the value A from memory location V, and thread two also takes the value A from memory location V and changes it to B, then changes it to A. At this point, the thread finds that A is still in memory, and then the operation is successful, but this process is problematic.

Solve the ABA problem, introduce the version number mechanism, you can use AtomicStampReference.

Published 15 original articles · praised 0 · visits 73

Guess you like

Origin blog.csdn.net/xrzi2015/article/details/105592403