Java multi-threading - Understanding the atomic issue and visibility issues from the perspective of memory model

First, from the operating system point of view to understand the program, process, thread

1.1 strongly recommended two blog posts, explained that the memory usage of Linux programs, processes, threads

Linux from a program to process: www.cnblogs.com/vamei/archi...

Linux Concurrency and synchronization: www.cnblogs.com/vamei/archi...

1.2 The figure is distributed in Java multithreading in memory. We recommended to walk above two articles and write well so direct referrals.

Heap (heap) are all threads in a process share for storing dynamic variables; each create a thread, the thread will be allocated to a stack, Thread stack is a unique thread, a thread can not access other thread stack ( local variables stored on the stack).

1.3 The following figure shows the Java heap and stack objects in the storage position

Second, multi-threading and memory problems atomicity visibility problems

2.1 Java memory model and hardware model

2.2 atomic visibility problems and problems

         Memory visibility problems , from 2.1 memory model and hardware model shows that each CPU has its own register (CPU Registers) and Cache (CPU Cache Memmory), run hardware thread is CPU, a thread operation of the main memory data when reading data starting with main memory, CPU calculates, but after the end of the operation, there may not be data will be stored main memory (RAM-main memory), so that other threads can not see the descending change data, which visibility has led to memory problems.
         Atomicity problem , as shown in FIG Race Condition goes on, the count variable is a shared variable, threads in the left and right operation count is count + 1, this operation is divided into three steps: read count value stored → count + 1 → count. Left thread after reading the count value of 1, are doing count + 1 Shi, read the thread count value of the right remains 1, also made the right thread count + 1, 1 + 1 but also so that when two When the thread is done in three steps, count 2 is not 3, so that the introduction of atomic issue. This step should be carried out in a manner three atoms (i.e., during the operation of the three steps, not other operations), such an operation is also called compound operation .

Guess you like

Origin juejin.im/post/5d7760ea5188250a9858240f