Java: Final field freeze on object reachable from final fields

前端 未结 5 621
不知归路
不知归路 2021-01-02 03:25

DZone refcard titled \"Core Java Concurrency\" states:

Once set, final field values cannot be changed. Marking an object reference field as final do

5条回答
  •  攒了一身酷
    2021-01-02 03:53

    The guarantee is stronger than you appear to think. The final field semantics apply even to mutable objects that are assigned to final fields (with the usual restrictions). SO extending your example to make A.b private and B mutable (but not externally mutable).

    public class A {
        private final B b = new B();
        public Integer get() { return b.c; }
    }
    
    public class B {
        public Integer c = 10;
    }
    

    In this case, A.get will never return null even under unsafe publication. Of course this example is completely abstract and therefore meaningless. Typically it is important for arrays (for instance in String) and collections.

提交回复
热议问题