java volatile 可见行(Visibility),原子性(Atomicity),有序性(Ordering)

Tue, Feb 16, 2021 2-minute read

prove java volatile visibility

image

Volatile

1.1 assume int number = 0; add volatile keyword before changing value of number

code:before add volatile keyword

package com.exa.study.thread;

import java.util.concurrent.TimeUnit;

class MyData {

    int number = 0;

    public void addTo60() {
        this.number = 60;
    }
}

/**
 *1.prove java volatile visibility
 * 1.1 assume int number = 0;  add volatile keyword before changing value of number
 */

public class VolatileDemo {

    public static void main(String[] args) {

        MyData myData = new MyData();

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName()+"\t come in");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (Exception e) {
                e.printStackTrace();
            }
            myData.addTo60();
            System.out.println(Thread.currentThread().getName()+"\t update number"+ myData.number);
        }, "AAA").start();

        // the second main thread
        while(myData.number == 0){
            // main thread would be waiting until number is not 0
        }

        System.out.println(Thread.currentThread().getName()+"\t umission is over");
    }
}

AAA come in AAA update number60

It shows main thread doesnot know the number has updated to 60.

code:add volatile keyword

class MyData {                  
                                
    volatile int number = 0;    
                                
    public void addTo60() {     
        this.number = 60;       
    }                           
}                                                               
image

Volatile

Java volatile keyword doesn’t means atomic

2.1 atomic :

  • An atomic operation is one that cannot be interrupted by the thread
  • method was executed successfully or failure

code:java volatile ≠ atomic

image

Volatile

atomic means the result would be 20000

However, when run the method twice, we can get two different result, means it is actually making non-atomic operation.

image

Volatile

image

Volatile