Reputation: 7427
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."
Upvotes: 4
Views: 325
Reputation: 4959
The obvious impact is some small performance impact because the compiler is forbidden from using certain optimizations. However the worse impact is the false sense of security. Just because a variable is volatile does not mean everything done with it is now threadsafe UNLESS all operations upon it are atomic (otherwise there could be a disconnect between the observation and the mutation of that variable).
Proper synchronization blocks are still needed. Your approach is inherently flawed. Sorry but it’s not that simple to get thread safety.
The third problem is it renders the true purpose of your code more obscure. If all variables are marked volatile then how is the reader to know which ones truly rely on that property and which ones don’t? Such obscurity creates a hidden cost in code maintenance burden, also known as “technical debt.”
Upvotes: 11
Reputation: 43391
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.
Upvotes: 7