1 PackageCom.javaee.corejava;2 /**3 * Thread-safe single-case mode4 * @authorMIAOYF5 *6 */7 Public classSingleton {8 /**9 * private static constant single-instance objectTen * Volatile: One * used in multi-threading, synchronous variables. thread to improve efficiency, a member variable (such as a) is copied a copy (such as B), A * The access to a in the thread is actually B. - * Synchronization of A and B is performed only in certain actions. Thus there is a and B inconsistency. Volatile is used to avoid this situation. - * Volatile tells the JVM that the variable it modifies does not keep the copy and accesses the main memory directly (that is, a above) the */ - Private Static volatileSingleton instance=NULL; - /** - * Privatization of constructors to prevent initialization by constructor functions + */ - PrivateSingleton () { + A } at /** - * Returns a singleton example - */ - Public StaticSingleton getinstance () { - if(instance==NULL){ - synchronized(Singleton.class) { in if(instance==NULL){ -Instance=NewSingleton (); to } + } - } the returninstance; * } $}
Java Singleton pattern implementation (thread safe)