Android classic Singleton mode and Android Classic Mode
SInstance is not initialized when the Singleton class is loaded for the first time. sInstance is initialized only when the Singleton getInstance method is called for the first time. Therefore, the first call to the getInstance method will result in
The SingletonHolder class is loaded on virtual machines. This method not only ensures thread security, but also ensures the uniqueness of the SingletonHolder object and also delays Singleton instantiation. Therefore, this is the recommended Singleton mode.
Public class Singleton {private Singleton () {}; public static Singleton getInstance () {return SingletonHolder. sInstance;}/*** static internal class */private static class SingletonHolder {private static final Singleton sInstance = new Singleton ();}}
Although this method seems to be quite good, it seems that the dual check lock (DCL) will fail.
public class MyImageLoader extends ImageLoader { private static MyImageLoader instance; public static MyImageLoader getInstance() { if (instance == null) { synchronized (MyImageLoader.class) { if (instance == null) { instance = new MyImageLoader(); } } } return instance; } protected MyImageLoader() { }}