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 {
p
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
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
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.
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
.
A volatile
field gives you guarantees as what happens when you change it. (No an object which it might be a reference to)
A final
field cannot be changed (What the fields reference can be changed)
It makes no sense to have both.
Because it doesn't make any sense. Volatile affects object reference value, not the object's fields/etc.
In your situation (you have concurrent map) you should do the field final
.