开发者

Partially constructed objects in non thread-safe Singleton

开发者 https://www.devze.com 2023-01-21 11:30 出处:网络
In a multi-threaded environment, how can a thread possibly see a \'partially constructed object\'? I understood that it is not thread-safe since multiple threads can create multiple instances.

In a multi-threaded environment, how can a thread possibly see a 'partially constructed object'? I understood that it is not thread-safe since multiple threads can create multiple instances.

class LazyInit
{  private static Resource resource = null;

    public static getInstance()
开发者_运维问答    {  if (resource == null) { resource = new Resource();  }
       return instance;
    }
}


Because of out-of-order writes.

If your constructor writes to non-final members, they don't have to be committed to memory right away, and actually they may even be committed after the singleton variable is. Java guarantees the thread that affects it sees the affectations in order, but not that other threads will unless you put a memory barrier.
See this question and this page of the Java specification for more information.

It might be beside the point but in your example, it is entirely possible that two threads see different singletons. Suppose one thread tests the nullity of the variable, enters the if and gets preempted before it gets a chance to construct the object. The new thread that gets the CPU now tests the yet-null object, constructs the singleton. When the old thread starts running again it will happily finish constructing the object and overwrite the singleton variable.
Another, more frightening issue, arises if the constructor of Resource calls for a method that will ultimately result in another call to this getInstance. Even if the state of the program results in no infinite loop, you will create several singleton instances.

0

精彩评论

暂无评论...
验证码 换一张
取 消