The code example which can prove “volatile” declare should be used

后端 未结 6 1119
别跟我提以往
别跟我提以往 2020-12-15 07:48

Currently I can\'t understand when we should use volatile to declare variable.

I have do some study and searched some materials about it for a long time

6条回答
  •  無奈伤痛
    2020-12-15 07:59

    The volatile keyword is pretty complex and you need to understand what it does and does not do well before you use it. I recommend reading this language specification section which explains it very well.

    They highlight this example:

    class Test {
        static volatile int i = 0, j = 0;
        static void one() { i++; j++; }
        static void two() {
            System.out.println("i=" + i + " j=" + j);
        }
    }
    

    What this means is that during one() j is never greater than i. However, another Thread running two() might print out a value of j that is much larger than i because let's say two() is running and fetches the value of i. Then one() runs 1000 times. Then the Thread running two finally gets scheduled again and picks up j which is now much larger than the value of i. I think this example perfectly demonstrates the difference between volatile and synchronized - the updates to i and j are volatile which means that the order that they happen in is consistent with the source code. However the two updates happen separately and not atomically so callers may see values that look (to that caller) to be inconsistent.

    In a nutshell: Be very careful with volatile!

提交回复
热议问题