Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partially constructed objects in non thread-safe Singleton

Tags:

java

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;
    }
}
like image 788
softwarematter Avatar asked Oct 19 '10 08:10

softwarematter


People also ask

Why is singleton pattern not thread-safe?

A singleton class itself is not thread safe. Multiple threads can access the singleton same time and create multiple objects, violating the singleton concept. The singleton may also return a reference to a partially initialized object.

Can singleton be thread-safe?

Thread Safe Singleton: A thread safe singleton is created so that singleton property is maintained even in multithreaded environment. To make a singleton class thread safe, getInstance() method is made synchronized so that multiple threads can't access it simultaneously.

How singleton works in multi threading applications?

In general, we follow the below steps to create a singleton class: Create the private constructor to avoid any new object creation with new operator. Declare a private static instance of the same class. Provide a public static method that will return the singleton class instance variable.

Are constructors thread-safe?

Constructors Are Not Thread-Safe.


1 Answers

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.

like image 81
Jean Avatar answered Oct 11 '22 08:10

Jean