From docs:
Using volatile variables reduces the risk of memory consistency errors
But this means that sometimes volatile variables don't work correct? Strange how it can be used - for my opinion it is very bad code that sometimes work sometimes not. I tried to Google but didn't find example memory consistency error with volatile. Could you please propose one?
Memory consistency errors occur when different threads have inconsistent views of what should be the same data. The causes of memory consistency errors are complex and beyond the scope of this tutorial. Fortunately, the programmer does not need a detailed understanding of these causes.
A volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread-safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem. The volatile keyword can be used either with primitive type or objects.
It improves thread performance. Synchronized methods degrade the thread performance. It synchronizes the value of one variable at a time between thread memory and main memory. It synchronizes the value of all variables between thread memory and main memory.
Volatile variables have the visibility features of synchronized but not the atomicity features. The values of the volatile variable will never be cached and all writes and reads will be done to and from the main memory.
The issue is not so much that volatile
works unreliably. It always works the way it is supposed to work. The problem is that the way it is supposed to work is sometimes not adequate for concurrency control. If you use volatile
in the wrong situation, you can still get memory consistency errors.
A volatile
variable will always have any writes propagated to all threads. However, suppose you need to increment the variable among various threads. Doing this(*):
volatile int mCounter;
// later, in some code that might be executed simultaneously on multiple threads:
mCounter++;
There is a chance that counter increments will be missed. This is because the value of mCounter
needs to be first read by each thread before a new value can be written. In between those two steps, another thread may have changed the value of mCounter
. In situations like this, you would need to rely on synchronized
blocks rather than volatile
to ensure data integrity.
For more info on volatile
vs. synchronized
, I recommend the article Managing volatility by Brian Goetz
(*) I realize that the above would be better implemented with AtomicInteger
; it's a contrived example to illustrate a point.
Volatile does the following:
- It prevents the caching the values in the Thread.
- It makes sure that the threads having the copies of the values of the fields of the object reconcile with the main copy present in the memory.
- Making sure the data is written directly to the memory and read from memory itself.
## But the condition where volatile fails:
- Making a Non-Atomic statement Volatile
.
Eg:
int count = 0;
count++; // Increment operator is Not Atomic in java
## Better option:
1. Its always better to follow the Brian's Rule
:
When ever we write a variable which is next to be read by another thread, or when we are reading a variable which is written just by another thread, it needs to be synchronized.
The shared fields must be made private, making the read and write methods/atomic statements synchronized.
2. Second option is using the Atomic Classes
, like AtomicInteger, AtomicLong, AtomicReference, etc.
## See this link, i have asked a similar question like yours:
Why Volatile is behaving weirdly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With