Search code examples
javamultithreadingvolatilecpu-cache

Is volatile keyword of any use if I run the application in single core machine?


I have recently getting myself familiarized with volatile keyword and I see that not reading from main memory directly can result in inconsistency and the so-called visibility problem.

I believe the CPU cache is not specific to any thread. So I was wondering if the volatile keyword will be of any use in singlecore processor?


Solution

  • Hardware-level concurrency is obviously an important part of the motivation for the spec, but the spec is quite clear that the requirements apply to the system as a whole; so, for example, the JVM's "just-in-time" (JIT) compiler can legitimately optimize the equivalent of

    while (this.var) {
        ... code that provably never modifies var ...
    }
    

    to the equivalent of

    if (this.var) {
        while (true) {
             ... code that provably never modifies var ...
        }
    }
    

    if var is not volatile.