How can I use the volatile keyword in Java correctly?

前端 未结 6 1980
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 14:31

Say I have two threads and an object. One thread assigns the object:

public void assign(MyObject o) {
    myObject = o;
}

Another thread uses t

6条回答
  •  南方客
    南方客 (楼主)
    2021-02-05 15:19

    I have spent quite a lot of time trying to understanding the volatile keyword. I think @aleroot has given the best and simplest example in the world.

    This is in turn my explanation for dummies (like me :-)):

    Scenario1: Assuming the stop is not declared as volatile then a given thread does and 'thinks' the following:

    1. stopWork() is called: I have to set the stop to true
    2. Great, I did it in my local stack now I have to update the main heap of JVM.
    3. Oops, JVM tells me to give a way in CPU to another thread, I have to stop for a while...
    4. OK, I am back. Now I can update the main heap with my value. Updating ...

    Scenario2: Now let the stop be declared as volatile:

    1. stopWork() is called: I have to set the stop to true
    2. Great, I did it in my local stack now I have to update the main heap of JVM.
    3. Sorry guys, I have to do (2) NOW - I am told it is volatile. I have to occupy CPU a bit longer...
    4. Updating the main heap ...
    5. OK, I am done. Now I can yield.

    No synchronization, just a simple idea...

    Why not to declare all variables volatile just in case? Because of Scenario2/Step3. It is a bit inefficient but still better than regular synchronization.

提交回复
热议问题