DEV Community

ChelseaLiu0822
ChelseaLiu0822

Posted on

Shared model memory

Java memory model

JMM is Java Memory Model, which defines the abstract concepts of main memory and working memory. The bottom layer corresponds to the CPU.
Registers, cache, hardware memory, CPU instruction optimization, etc.
JMM is reflected in the following aspects:
Atomic - Guarantees that instructions will not be affected by thread context switching
Visibility - Ensure instructions are not affected by CPU cache
Orderliness - ensures that instructions are not affected by CPU instruction parallel optimization

Visibility

Image description

Image description

Image description

  • Use volatile to solve visibility problems
    Volatile can use Ali to modify member variables or static member variables. It can prevent threads from caching their own work.
    To query the value of a variable in the main memory, you must obtain its value from the main memory. When threads operate volatile variables, they directly operate on the main memory.
    live

  • Locking can also solve visibility problems
    Modifications of volatile variables by one thread are visible to another thread, and atomicity cannot be guaranteed.
    The synchronized statement can not only ensure the atomicity of the code block but also ensure the visibility of the variables within the code block.
    The disadvantage is that synchronized is a heavyweight operation with relatively low performance.
    volatile is suitable for scenarios where one thread writes and multiple threads read.

Orderliness

The JVM can adjust the execution order of statements without affecting the correctness. This feature is called instruction redundancy.
Arrangement, and instruction rearrangement under multi-threading will affect correctness.

Top comments (0)