Search code examples
javaandroidmultithreadingconcurrencyvolatile

Unnecessarily using volatile keyword -- is that dangerous?


Is there ever any harm in making a variable "volatile" in Java if it doesn't actually need to be marked volatile? ... or is it just "unnecessary" as I have often read.

As someone dabbling in multi-threading, but not a master computer scientist, I'm currently going with "if in doubt, make it volatile."


Solution

  • It can have performance implications, but that's it.

    There may be another danger: that you lull yourself into thinking that since everything is volatile, your code is thread-safe. That's not the case, and there's no substitute for actually understanding the threading implications of your code. If you do that, you won't need to mark things volatile "just in case."

    But to your immediate question: no, you won't ever take functionally correct code and break it by making a variable violate.