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;
}
}
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 invokenewto 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.