Se Singleton Modèl Se sèlman yon sèl egzanp Ki te kreye nan Multi Threading

pandan w ap itilize modèl la Singleton, sèlman se yon sèl egzanp ki te kreye nan milti anfile?

Lè l sèvi avèk klas threadsafe Singleton pral garanti ke se sèlman yon sèl egzanp kreye.

piblik klas sele Singleton
{
estatik prive Singleton Singleton = nil;
prive estatik singletonLock objè rèdonli = nouvo objè();

prive Singleton() {}
estatik piblik Singleton GetInstance()
{
fèmen (singletonLock)
{
si (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.

Leave a Reply

Ou kapab sèvi ak sa yo tags HTML

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>