Java concurrency: is final field (initialized in constructor) thread-safe?

后端 未结 9 1083
暖寄归人
暖寄归人 2020-11-29 08:35

Can anyone tell me whether this class is threadsafe or not ?

class Foo {

    private final Map aMap;

    public Foo() {
        aMap =         


        
9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 09:18

    As it is described in Java Concurrency in Practice in section 16.3, this has to be thread-safe.

    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

    And an example from that section:

     @ThreadSafe
     public class SafeStates {
    
        private final Map states;
    
        public SafeStates() {
            states = new HashMap(); states.put("alaska", "AK");
            states.put("alabama", "AL");
            ...
            states.put("wyoming", "WY");
         }
    
         public String getAbbreviation(String s) { 
            return states.get(s);
         } 
     }
    

提交回复
热议问题