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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With