Double Check Lock
Package test;
public class Singleton {public
static Singleton Singleton;
Private Singleton () {
} public
static Singleton getinstance () {
if (singleton==null) {
synchronized ( Singleton.class) {
if (singleton==null) {
singleton=new Singleton ();
return singleton;
}
}
Return singleton
}
}
The first check in line 8th is to check whether Singleton is currently generated, and if so, do not sync, get Singleton directly, and save resources.
If the singleton is not generated, a new singleton instance is generated when the front thread locks the Singleton class.
The second check is to take into account such a situation.
Thread a detected in line 8th that Singleton was empty to line 11th to complete the singleton build, thread B also detected that Singleton was not empty, and was ready to enter the lock Singleton class.
Thread A completes the singleton class generation and releases the synchronization block. Thread B enters the synchronization, performs the detection on line 10th, and does not perform the build if Singleton has been generated.
To prevent thread B from saving a copy of the singleton value, you can define singleton as volatile so that each time you check the singleton, you need to reread the singleton value, and then write it again after each assignment.
As for thread-safe single case mode, you can use the enumeration class directly without this method.
All enumerated items are static final, meaning that they can only be constructed once and only once before they are used.
The instance of the enumeration entries is thread-safe, eliminating the need to consider things such as volatile,synchronized.
Package test;
*
* Using the global counter of the enumeration class
* Note that the instance construction is thread safe and unique. But the use of the method is not thread-safe.
* *
import Java.util.UUID;
public class Singletonusingenum {
enum singleton{
INSTANCE;
Unique identifier of the instance
private String id=uuid.randomuuid (). toString ();
private int counter;
Public String GetId () {return this
. Id;
}
public void Increment () {
counter++;
}
public int GetValue () {return
counter
}}
}