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

后端 未结 7 1213
我寻月下人不归
我寻月下人不归 2020-12-24 05:37

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 {

    p         


        
相关标签:
7条回答
  • 2020-12-24 05:50

    Because volatile and final are two extreme ends in Java

    volatile means the variable is bound to changes

    final means the value of the variable will never change whatsoever

    0 讨论(0)
  • 2020-12-24 05:51

    It's because of Java Memory Model (JMM).

    Essentially, when you declare object field as final you need to initialize it in object's constructor and then final field won't change it's value. And JMM promises that after ctor is finished any thread will see the same (correct) value of final field. So, you won't need to use explicit synchronization, such as synchronize or Lock to allow all threads to see correct value of final field.

    When you declare object's field as volatile, field's value can change, but still every read of value from any thread will see latest value written to it.

    So, final and volatile achieve same purpose -- visibility of object's field value, but first is specifically used for a variable may only be assigned to once and second is used for a variable that can be changed many times.

    References:

    • http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4

    • http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.4

    0 讨论(0)
  • 2020-12-24 05:57

    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.

    0 讨论(0)
  • 2020-12-24 05:58

    volatile is used for variables that their value may change, in certain cases, otherwise there is no need for volatile, and final means that the variable may not change, so there's no need for volatile.

    Your concurrency concerns are important, but making the HashMap volatile will not solve the problem, for handling the concurrency issues, you already use ConcurrentHashMap.

    0 讨论(0)
  • 2020-12-24 06:07

    A volatile field gives you guarantees as what happens when you change it. (No an object which it might be a reference to)

    A final field cannot be changed (What the fields reference can be changed)

    It makes no sense to have both.

    0 讨论(0)
  • 2020-12-24 06:09

    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.

    0 讨论(0)
提交回复
热议问题