Alex Rivera | Logout

Why can an Object member variable not be both final and volatile in Java?

Asked 2012-02-17T12:32:49.683
55

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?

Edit
Report

2 Answers

3

volatile modifier guarantees that all reads and writes go straight to main memory, i.e. like the variable access is almost into synchronized block. This is irrelevant for final variable that cannot be changed.

answered 2012-02-17T12:38:46.843
2

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.

answered 2012-02-17T12:37:18.643

Your Answer