When the Singleton class is loaded for the first time, Sinstance is not initialized, only when the GetInstance method of Singleton is called for the first time, which causes sinstance to be initialized. Therefore, calling the GetInstance method for the first time causes
The virtual machine loads the Singletonholder class, which not only ensures thread safety, but also ensures uniqueness of singleton objects and also delays the instantiation of Singleton, so this is the recommended singleton mode
public class Singleton { private Singleton () {}; public static Singleton getinstance () { return singletonholder.sinstance; } /** * Static inner class */ private static class singletonholder{ private static final Singleton sinstance = new Singl Eton (); }}
This method may seem like a good one, but there seems to be a double check lock (DCL) failure.
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 () { }}
Android Classic single-case mode