I have read “When to use ‘volatile’ in Java?” but I’m still confused. How do I know when I should mark a variable volatile? What if I get it wrong, either omitting a volatile on something that needs it or putting volatile on something that doesn’t? What are the rules of thumb when figuring out what variables should be volatile in multithreaded code?
Share
You basically use it when you want to let a member variable be accessed by multiple threads but do not need compound atomicity (not sure if this is the right terminology).
the above is a bad example, because you need compound atomicity.
Now to a valid example:
Now, why can’t you just use
private static int temperature? In fact you can (in the sense that that your program won’t blow up or something), but the change totemperatureby the other thread may or may not be “visible” to the main thread.Basically this means that it is even possible that your app. keeps writing
Today's temperature is 0forever if you don’t usevolatile(in practice, the value tends to become eventually visible. However, you should not risk not using volatile when necessary, since it can lead to nasty bugs (caused by in-completely constructed objects etc.).If you put
volatilekeyword on something that doesn’t needvolatile, it won’t affect your code’s correctness (i.e. the behaviour will not change). In terms of performance, it will depend on the JVM implementation. In theory you might get a tiny performance degradation because the compiler can’t do reordering optimisations, have to invalidate CPU cache etc., but then again the compiler could prove that your field cannot ever be accessed by multiple threads and remove the effect ofvolatilekeyword completely and compile it to identical instructions.EDIT:
Response to this comment:
You can and it will behave correctly. Anything that you can with
volatilecan be done withsynchronized, but not vice versa. There are two reasons you might prefervolatileif you can:volatileis less prone to concurrency bugs, like blocking while holding the lock, deadlocks etc.volatilecan have significantly higher throughput and better latency. However in most applications the difference is too small to matter.