JMM (JAVA Memory Model) Java memory model and volatile

tags: java  JMM  volatile  

JMM basics-computer principles


Calculate a+b
The CPU reads the memory 100ns once, and it takes 200ns to read a and b
CPU calculation only takes 0.6ns
Most of the time executing a+b is waiting to read memory
So the introduction of high-speed cache (first, second, third)
Multi-core CPU sharing L3

L1 is the fastest and the smallest capacity

In order to improve the running speed, cache is introduced
In order to make full use of cache, JMM was proposed

Java Memory Model (JMM)

Working memory, main memory, two abstract concepts
Working memory: Including CPU internal registers, cache, and part of main memory (RAM), a small part of which is in main memory
Main memory: a small part may be in registers and cache

If the variable count is accumulated
count is in main memory
When any thread wants to accumulate, it will put count in the thread's unique working memory, and each thread that operates count has a copy of count
The thread is only allowed to operate on the count in the thread's working memory, and is not allowed to directly manipulate the variables in the main memory
The working memory of each thread is exclusive
Heap memory is understood as main memory, and stack memory is understood as working memory

Concurrency security issues caused by JMM

VariableVisibility, atomicity
The initial value of count is 0
Two threads calculate count = count + 1
The result should be 2, but the result may be 1

The two threads do not know that the other side has modified the thread, and cannot see the other side’s modification of count, there is a visibility problem

How to solve the visibility problem?

volatile

1. Force a variable to be read from main memory
2. Whenever the variable is modified, it is forced to refresh to the main memory immediately

Volatile can only guarantee visibility

Volatile cannot solve our security problems. Volatile is only for forced reading and writing. The problem is that the calculation process is not an atomic operation.

Synchronized guarantees visibility and atomicity at the same time, and the strength of synchronized is greater than that of volatile
Volatile is the most lightweight synchronization mechanism provided by the JDK

A single read/write of a volatile variable can be regarded as using the same lock to synchronize these single read/write operations

The volatile variable itself has the following characteristics:
Visibility: Reading a volatile variable can always see (any thread) the last write to this volatile variable.
Atomicity: For anysingleThe read/write of volatile variables is atomic, but similar to volatile++complexThe operation is not atomic.

Pipeline and reordering:
cpu can execute multiple instructions at once

do(){
    int a = 5 ;
    int b = 6 ;
    int c = 7 ;
    int d = a ;
    if( b == 6){
      d = b;
    }
}

In our impression, the cpu is executed sequentially. After the introduction of pipeline and reordering, the cpu may execute all four at once, and may do the d = b before if (b == 6), and calculate the first Things are opened in memoryReorder cacheIf there is an if (b == 6), put the result of the reordering cache directly in it, not necessarily after the if

Intel cpu can support up to ten stages of pipelines, and can execute 10 instructions at the same time
Android ARM architecture three-stage pipeline, 3 instructions can be executed at the same time

Reordering changes the meaning of the order in which we write code. Single thread must meet our requirements, and multithreading may cause confusion.
Volatile suppresses reordering

Application scenarios of volatile:
When only one thread writes and multiple threads read, volatile is no problem to use. You can force the writing thread to flush to the main memory, otherwise you don’t know when to flush to the main memory. Forced reading can see the latest variables (visibility)
Multiple threads cannot guarantee atomicity when writing to a variable
There is no correlation between write operations, volatile can be used without problems

Many uses in JDK concurrency tools: volatile + CAS to replace synchronized
Volatile can be understood as lock-free programming

The realization principle of volatile

Shared variables modified with volatile variables will use the Lock prefix instruction provided by the CPU when writing operations
1. Write the data of the current processor cache line back to the system memory
2. This operation of writing back to the memory will invalidate the data cached at the memory address in other CPUs

Intelligent Recommendation

JMM--Java memory model

JMM The Java Memory Model (JMM) itself is an abstract concept that does not exist. It describes a set of rules or specifications that define how each variable in a program is accessed. Since the entit...

--- JMM Java Memory Model

JMM Profile On a physical machine, since the speed of the read and write registers on the processor orders of magnitude faster than memory, the speed in order to solve this contradiction, between whic...

JMM (java memory model)

The article is quite good: in a multithreaded environment to be communicated between the threads, have to mention JMM (java memory model) in the java memory model (JMM) inside the memory used by the J...

JMM Java Memory Model

What is the JMM That JMM Java Memory Model is a memory model specifications; to ensure that the Java program in a variety of platforms to access memory can ensure consistent results. Why should JMM Du...

JMM: Java memory model

JMM The concept of the Java memory model Java Memory Molde (Java Memory Model / JMM), don't confuse it with Java memory structure The Java memory model is a memory model defined in the Java Virtual Ma...

More Recommendation

JMM-Java memory model

Origin of JMM The Java language specification stipulates that the JVM must maintain internal threads similar to a sequential language: As long as the final result of the program is equal to the result...

Exception Handling in Spark Data Frames

http://anishc.me/spark/exception-handling-spark-data-frames/   Exception Handling in Spark Data Frames  7 minute read General Exception Handling Handling exceptions in imperative programming...

Python - Django Project Development: Configuration Project / Static / Path, Call CSS, IMG, JS and other static files

In Django project development, you cannot access local static files through 'Imgs / Bg.jpg' like normal web development, and you need to do some configurations to achieve access to static files. First...

Everything is an object

according totypeofThe output we can see (undefined, number, string, boolean) is a simple value type and the remaining output is aobjectThey are all reference objects. Everything (reference type) is an...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top