Java: Final field freeze on object reachable from final fields

前端 未结 5 598
不知归路
不知归路 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:55

    Java Concurrency in Practice mentions this in section 16.3:

    Initialization safety guarantees that for properly constructed objects, all threads will see the correct values of final fields that were set by the constructor, regardless of how the object is published. Further, any variables that can be reached through a final field of a properly constructed object (such as the elements of a final array or the contents of a HashMap referenced by a final field) are also guaranteed to be visible to other threads. For objects with final fields, initialization safety prohibits reordering any part of construction with the initial load of a reference to that object. All writes to final fields made by the constructor, as well as to any variables reachable through those fields, become “frozen” when the constructor completes, and any thread that obtains a reference to that object is guaranteed to see a value that is at least as up to date as the frozen value. Writes that initialize variables reachable through final fields are not reordered with operations following the post-construction freeze.

提交回复
热议问题