Why can an Object member variable not be both final and volatile in Java?
If in a class I have a ConcurrentHashMap instance that will be modified and read by multiple threads I might define like this:
public class My Class {
private volatile ConcurrentHashMap<String,String> myMap = new ConcurrentHashMap<String,String>();
...
}
adding final
to the myMap field results in an error saying I can only use final or volatile. Why can it not be both?
volatile
only has relevance to modifications of the variable itself, not the object it refers to. It makes no sense to have a final volatile
field because final fields cannot be modified. Just declare the field final
and it should be fine.
It's because of Java Memory Model (JMM).
Essentially, when you declare object field as final
you need to initialize it in object's constructor and then final
field won't change it's value. And JMM promises that after ctor is finished any thread will see the same (correct) value of final
field. So, you won't need to use explicit synchronization, such as synchronize
or Lock
to allow all threads to see correct value of final
field.
When you declare object's field as volatile
, field's value can change, but still every read of value from any thread will see latest value written to it.
So, final
and volatile
achieve same purpose -- visibility of object's field value, but first is specifically used for a variable may only be assigned to once and second is used for a variable that can be changed many times.
References:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.4
Because volatile
and final
are two extreme ends in Java
volatile
means the variable is bound to changes
final
means the value of the variable will never change whatsoever
volatile
is used for variables that their value may change, in certain cases, otherwise there is no need for volatile
, and final
means that the variable may not change, so there's no need for volatile
.
Your concurrency concerns are important, but making the HashMap
volatile will not solve the problem, for handling the concurrency issues, you already use ConcurrentHashMap
.