Java multi-thread memory visibility

Source: Internet
Author: User

Visibility: A thread changes the value of a shared variable to be seen by other threads in a timely manner.

Shared variables: If a variable has a copy in the working memory of multiple threads, then this variable is a shared variable for these threads.

All of the variables are stored in main memory


Java memory model (JVM)

    • 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 provisions

    • All operations of a thread on a shared variable must be made in its own working memory and cannot be read and written directly from the main memory.
    • Variables in the working memory of other threads cannot be accessed directly between different threads, and the transfer of variable values between threads needs to be done through main memory.


The principle of shared variable visibility implementation
Thread 1 modification of shared variables to be seen in time by thread 2, there are 2 steps to follow:

    • 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


to achieve the visibility of shared variables, two points must be guaranteed:
    • Thread-Modified shared variable value can be flushed from working memory to main memory in a timely manner
    • Other threads can update the current value of shared variables from main memory to their working memory in time

how visibility is implemented
The implementation of visibility is supported at the Java language level:
    • Synchronized
    • Volatile

Synchronized achieving visibility
Synchronized can achieve:
    • Atomicity (synchronous)
    • Visibility of
The JVM's two rules 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 shared variable needs to be re-read from the main memory (note: Locking and unlock need to be the same lock)
The process by which threads execute mutually exclusive code:
    1. Obtaining a mutex lock
    2. Empty working memory last year
    3. Copy the most recent copy of the variable from the main memory to the working memory
    4. Execute code
    5. Refreshes the value of the changed shared variable into main memory
    6. Release Mutex lock
public class Synchronizeddemo {private Boolean ready = false;private int result = 0;private int number = 1;/** * Write operation */pub LIC void Write () {ready = True;//1.1number = 2;//1.2}/** * Read operation */public Void Read () {if (ready) {//2.1result = number*3;//2.2} SYSTEM.OUT.PRINTLN ("Result value is:" +result);} Private class Readwritethread extends Thread{private boolean flag;public readwritethread (Boolean flag) {This.flag = flag;} @Overridepublic void Run () {if (flag) {///constructor passed in true, writes write ();} else{//constructs a method to pass in true, to perform a read operation reading ();}} public static void Main (string[] args) {Synchronizeddemo demo = new Synchronizeddemo ();//start thread to perform write operations demo.new Readwritethread (True). Start ();//start thread to perform read operation Demo.new Readwritethread (FALSE). Start ();}}

volatile for visibility
volatile keyword:
    • Can guarantee the visibility of volatile variables
    • The atomicity of volatile variable compound operations cannot be guaranteed
How volatile can achieve memory visibility:
In-depth: This is done by the memory barrier and the Disable reordering optimization.
    • When a write operation is performed on a volatile variable, a store barrier command is added after the write operation
    • When a read operation is performed on a volatile variable, a load barrier command is added before the read operation
In layman's terms: the volatile variable is forced to reread the value of the variable from main memory each time it is accessed by the thread.
When the variable is changed, it forces the thread to flush the most recent value into main memory.
At any point in time, different threads can always see the latest value of the variable.

The process by which threads write volatile variables:
    1. Changing the value of a copy of a volatile variable in a thread's working memory
    2. Refreshes the changed copy value from the working memory to the main memory
The process by which threads read volatile variables:
    1. Reads the latest value of the volatile variable from the main memory into the working memory of the thread
    2. Read a copy of a volatile variable from the working memory
Volatile does not guarantee that volatile variables conform to the atomic nature of the operation:
private int Number= 0;synchronized( This){
Number+ +: not atomic operation Number++;
    1. Reads the value of number}
    2. Add the value of Number 1 to synchronized, to atomic operation
    3. Write the value of the latest number private volatile int # = 0;
change to volatile variable, no guarantee of atomicity
public class Volatiledemo {private volatile int number = 0;public int GetNumber () {return this.number;} public void Increase () {this.number++;} public static void Main (string[] args) {Final Volatiledemo demo = new Volatiledemo (), for (int i = 0;i<500;i++) {New Threa D (New Runnable () {@Overridepublic void run () {demo.increase ();}}). Start ();;} If there are sub-threads running, the main thread will give the CPU resources//until all the child threads run out, the main thread continues to execute while (Thread.activecount () >1) {Thread.yield ();} System.out.println ("Number:" +demo.getnumber ());}}


synchronized and volatile comparison
    • Volatile does not require locks, is more lightweight than synchronized, does not block threads
    • From a memory visibility perspective, volatile reads are equivalent to locking, and volatile writes are equivalent to unlocking
    • Synchronized can guarantee both visibility and atomicity, while volatile only guarantees visibility and cannot guarantee atomicity


Java multi-thread memory visibility

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.