volatile Java learning record of concurrent

Disclaimer: This article is a blogger original article, reproduced, please attach Bowen link! https://blog.csdn.net/Little_fxc/article/details/87938990

volatile Java learning record of concurrent

First, let's perceptual knowledge:

  • volatileKeyword atomicity only the original variables (e.g. boolen, short, int, long, etc.) assignment,
    but such a combined operation i++is not guaranteed.

The difference between volatile and synchronized

volatileThe key is to solve the problem of visibility of memory, it will make all the reading and writing will be on the volatile variable brush directly to the main memory,
which is to ensure the visibility of variables.
So that we can meet some of the variables have the visibility requirements of the order does not require reading needs.

synchronizedThe key is to solve the problem of execution control, it will prevent other threads to get the current monitor lock of the object,
so that makes the current object code block synchronized keyword is protected and can not be accessed by other threads, it can not be executed concurrently.
More importantly, synchronizedwill create a memory barrier, memory barrier command ensures that all CPU operating results will brush directly to the main memory,
thus ensuring the visibility of memory operations, but also makes all operations to obtain the lock thread ,
both happens-before and then get to the lock thread operation.

Point of difference

  1. volatileEssentially telling the JVM current variable values in register (working memory) is uncertain, needs to be read from the main memory;
    synchronizedthe current variable is locked, only the current thread can access the variables, other threads are blocked to live.

  2. volatileCan only be used in variable level; synchronizedit can be used in the variables, methods, and the class level.

  3. volatileVisibility can be achieved only modify variables, it does not guarantee atomicity;
    and synchronizedcan be modified to ensure the visibility of the atoms and variables.

  4. volatileIt will not cause obstruction thread; synchronizedmay cause obstruction thread.

  5. volatileVariable mark will not be optimized compiler; synchronizedvariable mark may be optimized compilers

  6. volatileKeyword is used to solve the visibility of variables between multiple threads, and the synchronizedkey solution is to access resources between multiple threads synchronization.

volatile visibility

The following is added a volatilekeyword and without volatiledistinction keyword mapping demo:

Here Insert Picture Description

The difference is that, volatile modified member variable each time it is accessed threads
are forced to re-read the value of the member variable from main memory (shared memory) in.
Also, when members of the variable changes, forcing thread will change the value written back to main memory (shared memory).
So that at any moment, two different threads always see the same value of a member variable, which will ensure the visibility of synchronous data.

Visibility of verification volatile

package com.littlefxc.examples.base.thread;

/**
 * @author fengxuechao
 * @date 2019/2/21
 **/
public class VolatileSample extends Thread {

    private int number;

    static boolean ready = true;

    @Override
    public void run() {
        while (ready) {
            number++;
        }
        System.out.println(ready);
        System.out.println(number);
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new VolatileSample();
        t1.start();
        Thread.sleep(1000);
        ready = false;
    }
}

The code above, I do not have to readyadd variables volatilekeyword, after running into an infinite loop.

To readyadd a keyword variable volatilerunning again after modification program, to stop in time, there is no infinite loop.

Validation results:

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/Little_fxc/article/details/87938990