First of all, recommend the best way to implement the Singleton mode (no one)
public class Manager {
Private Manager () {
}
public static Manager getinstance () {
return managerholder.instance;
}
private Static Class Managerholder {
Private static final Manager instance = new manager ();
}
}
Then explain why this is the way:
* The inner class is loaded by the ClassLoader only when needed, enabling lazy loading, which is to instantiate a manager when needed, and is the only one
* Also because instance is a static final type, ensuring that only one instance exists in memory and can only be assigned once, ensuring thread safety
(Even if multiple threads concurrently access the getinstance () method in high concurrency, the instance's uniqueness can be guaranteed)
Other implementations that do not adopt an inner class are the best they have seen at this time:
public static class Singletonoptimizelazy {
static Singletonoptimizelazy instance = NULL;
public static Singletonoptimizelazy getinstance () {
if (instance = = null) {
CreateInstance ();
}
return instance;
}
Private synchronized static Singletonoptimizelazy CreateInstance () {
if (instance = = null) {
Instance = new Singletonoptimizelazy ();
}
return instance;
}
}
The main idea of this solution is to abstract the process of instantiation into a sychronized method so that lazy loading and concurrency security can also be implemented.
However, it is still recommended to use the internal class solution
Java design Pattern-Singleton mode-Lazy loading