Creating Object in a thread safety way

2020-05-29 00:49发布

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

Warning: When constructing an object that will be shared between threads, be very careful that a reference to the object does not "leak" prematurely. For example, suppose you want to maintain a List called instances containing every instance of class. You might be tempted to add the following line to your constructor:

instances.add(this);

But then other threads can use instances to access the object before construction of the object is complete.

Is anybody able to express the same concept with other words or another more graspable example?

Thanks in advance.

8条回答
\"骚年 ilove
2楼-- · 2020-05-29 01:53

Thread A is creating Object A, in the middle of creation object A (in first line of constructor of Object A) there is context switch. Now thread B is working, and thread B can look into object A (he had reference already). However Object A is not yet fully constructed because Thread A don't have time to finish it.

查看更多
Summer. ? 凉城
3楼-- · 2020-05-29 01:54

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.

查看更多
登录 后发表回答