terwyl die gebruik van die Singleton patroon, slegs een voorbeeld is geskep in 'n multi-threading?
Met behulp van threadsafe Singleton klas sal verseker dat slegs een voorbeeld is geskep.
openbare verseël klas Singleton
{
private statiese Singleton Singleton = null;
private statiese readonly voorwerp singletonLock = nuwe voorwerp();
private Singleton() {}
openbare statiese Singleton GetInstance()
{
sluit (singletonLock)
{
indien (singleton == null)
{
singleton = new Singleton();
}
return singleton ;
}
}
}
Issue will raise only when the creation of first instance.
Using lock() will provide us the thread safe to avoid execution of two threads at a same time to create instance.
Again we are verifying the (singletonobject == null) so it will guarantee that only once instance will be created.
double check option will be full proof for our class.
Laat 'n Antwoord