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 myMap = new ConcurrentHashMap();
...
}
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.