Singleton mode of a variant: double-checked Locking

zhaozj2021-02-08  490

Singleton mode of a variant: double-checked Locking

Under the single thread, our Singleton is like this (Java):

Class singleton {

PRIVATE SINGLETON () {// ...};

Private static singleton instance = null;

Public Static Singleton GetInstance

{

IF (instance == null)

Instance = new singleleton ();

Return Instance;

}

// ...

}

But in a multi-threaded environment, there is a problem: if a thread checks instance == null, then start creating a new instance; at the same time, another thread checks instance == NULL (creation of the first thread at this time Still not completed, then create a new instance. This has two instances of the Singleton class - our Singleton mode failed.

So we should join the synchronization code. But where is it? If each thread needs to get synchronous and then get an instance reference, it will inevitably form a bottleneck; if you check the synchronization code after the check of instance == null ... This is not used. why? Think you think about it.

What should we do? Synchronous code is definitely behind instance == null, at the same time, you should check once before creating a new object, == null:

Class singleton {

// ...

Private synchronized static void dosync () {

// Synchronize here

}

Public Singleton getInstance () {

IF (instance == null) {

Singleton.dosync ();

IF (instance == null) // once check

Instance = new singleleton ();

}

Return Instance;

}

Two inspections, avoiding efficiency bottlenecks, avoiding repeated creation. This is the double-checked loching mode.

转载请注明原文地址:https://www.9cbs.com/read-498.html

New Post(0)