Alb Alb - 9 months ago 62
Java Question

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>();

to the myMap field results in an error saying I can only use final or volatile. Why can it not be both?

Answer Source

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.