3
Java Volatile Keyword Explained by Example - DZone Java (dzone.com)
natsu 積分 0 編輯於

這個情境真的很難重現,主要是要讓 thread 夠忙來不及更新資料才會發生 ...

就算只是單純的把 System.out 移到外面來,也會影響執行結果:

public class VolatileTest {
    private static volatile int MY_INT = 0;

    public static void main(String[] args) {
        new ChangeListener().start();
        new ChangeMaker().start();
    }

    static class ChangeListener extends Thread {
        @Override
        public void run() {
            int local_value = MY_INT;
            while ( local_value < 5){
                if( local_value!= MY_INT){
                    //LOGGER.log(Level.INFO,"Got Change for MY_INT : {0}", MY_INT);
                    //System.out.println("Got Change for MY_INT : " + MY_INT);
                    local_value= MY_INT;
                }
                //原本是 local_value != MY_INT 才會印出 Got Change ...
                System.out.println("Got Change for MY_INT : " + MY_INT);
            }
        }
    }

    static class ChangeMaker extends Thread{
        @Override
        public void run() {

            int local_value = MY_INT;
            while (MY_INT <5){
                //LOGGER.log(Level.INFO, "Incrementing MY_INT to {0}", local_value+1);
                System.out.println("Incrementing MY_INT to " + (local_value+1));
                MY_INT = ++local_value;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) { e.printStackTrace(); }
            }
        }
    }
}
kaif 積分 0

比較精確的說是為了最佳化,值保存在L1 cache,沒有sync回L2/memory。有誤請指正。

另外這應該是比較節儉的語言才會有這種最佳化吧,好像golang python什麼的不會有這種狀況。