Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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."

like image 347
Nerdy Bunz Avatar asked Dec 01 '22 10:12

Nerdy Bunz


1 Answers

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.”

like image 200
Patrick Parker Avatar answered Dec 03 '22 22:12

Patrick Parker