Creating Object in a thread safety way

前端 未结 8 2242
再見小時候
再見小時候 2021-02-06 12:50

Directly from this web site, I came across the following description about creating object thread safety.

Warning: When constructing an object that will b

8条回答
  •  清歌不尽
    2021-02-06 13:14

    I think that the following example illustrate what authors wanted to say:

    public clsss MyClass {
        public MyClass(List list) {
            // some stuff 
    
            list.add(this); // self registration
    
            // other stuff 
        }
    }
    

    The MyClass registers itself in list that can be used by other thread. But it runs "other stuff" after the registration. This means that if other thread starts using the object before it finished its constructor the object is probably not fully created yet.

提交回复
热议问题