Simplest and understandable example of volatile keyword in Java

后端 未结 12 868
梦谈多话
梦谈多话 2020-11-28 19:43

I\'m reading about volatile keyword in Java and completely understand the theory part of it.

But, what I\'m searching for is, a good case example, which sho

12条回答
  •  悲&欢浪女
    2020-11-28 20:43

    volatile is not going to necessarily create giant changes, depending on the JVM and compiler. However, for many (edge) cases, it can be the difference between optimization causing a variable's changes to fail to be noticed as opposed to them being correctly written.

    Basically, an optimizer may choose to put non-volatile variables on registers or on the stack. If another thread changes them in the heap or the classes' primitives, the other thread will keep looking for it on the stack, and it'll be stale.

    volatile ensures such optimizations don't happen and all reads and writes are directly to the heap or another place where all threads will see it.

提交回复
热议问题