Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this singleton construction code NOT thread safe?

In this code, why has been written "Not thread safe"? Thank you

class Singleton
{
  private static Singleton _instance;

  // Constructor is 'protected'
  protected Singleton()
  {
  }

  public static Singleton Instance()
  {
    // Uses lazy initialization.
    // **Note: this is not thread safe.**
    if (_instance == null)
    {
      _instance = new Singleton();
    }

    return _instance;
  }
}
like image 826
odiseh Avatar asked Sep 21 '10 05:09

odiseh


1 Answers

If two threads run the if (_instance == null) check at the same time while there's no singleton instance created, they will both try to invoke new to create the singleton instance and store the references to them into the same variable.

Since the reference they will try to store to will be shared between threads this action will not be thread-safe. Also it might happen that creating two instances of the singletone class will break the program.

like image 104
sharptooth Avatar answered Oct 25 '22 11:10

sharptooth