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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With