Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 272
Alb Avatar asked Feb 17 '12 12:02

Alb


People also ask

Can a variable be both static and volatile in Java?

Yes, you can. A static variable in Java is stored once per class (not once per object, such as non-static variables are). This means all your objects (and static methods) share the same variable.

Should all variables be volatile?

So to answer your question, no, if a variable is written to within a synchronized block, you don't need to mark it volatile , provided that you always read that variable from a synchronized block using the same monitor.

What will happen if we declare the variable as volatile in Java?

For Java, “volatile” tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself.

Can objects be volatile in Java?

The volatile keyword can be used either with primitive type or objects. The volatile keyword does not cache the value of the variable and always read the variable from the main memory. The volatile keyword cannot be used with classes or methods. However, it is used with variables.


1 Answers

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.

like image 54
Michael Borgwardt Avatar answered Oct 04 '22 01:10

Michael Borgwardt