Synchronize to ensure that reference to immutable object will be seen by another thread

后端 未结 4 2069
温柔的废话
温柔的废话 2021-01-06 15:01

I was studying this to understand the behavior of final fields in the new JMM (5 onwards). This concept is clear: guaranteed visibility of initialized final fields to all t

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-06 15:06

    Making all the fields final will ensure they are published to other threads properly. That comment is probably referring to the following scenario:

    private myField;
    
    public void createSomething()
    {
        myField = new MyImmutableClass();
    }
    

    In this case you still need proper synchronization around any access to myField, or other threads might never see the newly created object.

提交回复
热议问题