Search code examples
javamultithreadingvolatilesingle-threaded

Is volatile useful at all in a singlethreaded application in Java?


As in the title - is there any case in which volatile is useful in the context of single-thread programming in Java? I know it's used to make sure the value of the variable is always actually checked in memory so is there any case in which that value may change (in a singlethreaded application) in a way that the app/compiler won't notice?


Solution

  • No, at least not for your own defined variables in a single-threaded application.

    The volatile keyword guarantees happens-before relationships with multiple reads of that variable, which only makes sense when multiple threads access it.

    Additional insights here.