Detail the memory visibility of Java multi-thread

Source: Internet
Author: User
Tags volatile

Programming the knowledge and skills of these practices, every learning use may have a new understanding I. detail of Java Multi-thread memory visibility (data earned) 1. visibility of shared variables between threads Shared variables : If a variable has a copy in the working memory of multiple threads, then this variable is the shared variable of these threads. Visibility : A thread changes the value of a shared variable to be seen by other threads in a timely manner Java memory model (Jmm,java): describes the access rules for various variables (thread-shared variables) in Java programs, and in the JVM the underlying details such as variables are stored in memory and read out in memory. all of the variables are stored in main memory each thread has its own independent working memory, which holds a copy of the variable used by the thread ( a copy of the variable in main memory )                       Article two stipulates : All operations of a thread on a shared variable must be in its own working memory (working, an abstraction of the cache and register, not a part of memory, /c1> This explanation stems from "Concurrent programming in Java:design principles and Patterns, Second Edition" §2.2.7, Original: Every thread is de Fined to has a working memory (an abstraction of caches and registers) in which to store values. A lot of people think that working memory is a part of the RAM, which may be translated into working memory for the sake of work, in order to avoid confusion, this is called the work store, each thread has its own work storage ), Cannot read and write directly from each other's memory                           variables in the working memory of other threads cannot be accessed directly between different threads, inter-thread variables are worth passing through main memory to complete The implementation principle of shared variable visibility Flush Shared variables updated in working memory 1 to main memory updates the value of the most recent shared variable in main memory to work memory 2 The implementation of visibility is supported at the Java language level : synchronized volatile final can also guarantee memory visibility 2. Synchronized achieve visibility You can implement mutexes (atomicity), which is synchronization. But many people ignore the feature of their memory visibility JMM Two provisions on synchronized:The current value of the shared variable must be flushed to main memory before the line threads unlocked line Cheng, the value of the shared variable in the working memory is emptied, so that the most recent value needs to be re-read from memory when using shared variables ( Note: Locking and unlocking need to be the same lock ) changes to shared variables before line threads unlocked visible to other threads as shown in chess armor                 · Causes of shared variables not being visible between threads : 1. Cross-execution of threads (guaranteed atomicity , use of synchronized keyword) 2. Reordering with thread cross-execution ( atomicity ) 3. Shared variable updated values are not updated in time between working memory and main memory ( visibility )In the Java runtime, the execution engine tries to try to figure out what the user is trying to do, so most of the time you will see the correct results, but even if only one unpredictable result can have a significant impact, we must ensure that the thread is secure when we need memory visibility. 3, volatile realization of visibility               · Order reordering the order in which the code is written differs from the order in which it is actually executed, which is the compiler or processor optimized for improved program performance 1. Compiler-Optimized reordering (compiler Optimizations) 2. Instruction-level parallel reordering (processor optimization) 3. Re-sequencing of memory systems (processor optimization) reordering does not give a single thread a problem with memory visibility (because as-if-serial semantics) reordering may cause memory visibility issues when programs are interleaved in multiple threads as-if-serial semantics no matter how to reorder, the results of the program execution should be the same as the result of sequential execution (Java the compiler, runtime, and processor will ensure that Java follows as-if-serial semantics in a single thread )                              · use of volatile keyword considerations 1. can guarantee the visibility of volatile variables (the principle is similar to the Synchronized keyword principle) in depth, memory visibility is achieved by adding memory barriers and preventing reordering optimizations. When a write operation is performed on a volatile variable, a store barrier instruction is added after the write operation, and a load barrier command is added to the read operation when a read operation is performed on the volatile variable. 2. atomicity of volatile variable compound operations cannot be guaranteed int num = 0; num++;//++ Operation Non-atomic operation, 3 step execution methods of guaranteeing atomicity: Synchronized Keywords Reentrantlock An incoming lock object Atomicinterger Object 3.volatile applicable occasions using volatile variables safely in multiple threads must satisfy two conditions:① writes to a variable do not depend on its current value, such as number++. A boolean variable can ② The variable is not contained in the invariant with other variables, if there are multiple volatile variable, each volatile variable must be independent of the other volatile variables 4, synchronized and volatile comparison volatile does not require locks, is more lightweight than synchronized, does not block threads, and is more efficient from a memory visibility perspective, volatile reads are equivalent to locking, and volatile writes are equivalent to unlocking synchronized skills guarantee visibility, while guaranteeing atomicity, while volatile only guarantees visibility and does not guarantee atomicity. If you can solve the problem with volatile, you should try to use volatile, because it is more efficient one point to be aware of: Q: Even if there are no guaranteed visibility measures, many times a shared variable can be updated in the main memory and working memory in a timely manner? A : Generally only in a short period of time high concurrency in the case of the variable can not be updated in a timely manner, because the CPU in the execution will be quickly refreshed cache, it is generally difficult to see this problem, but also with the hardware performance has a great relationship, so the results are unpredictable, formally because unpredictable, That's why we want to keep the thread safe . another: In Java, Long, double is 64-bit, its read and write will be divided into two 32-bit operation, not atomic operation, but many commercial virtual machines are optimized, so, understand can



From for notes (Wiz)



Detail the memory visibility of Java multi-thread

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.