Singleton mode refers to a class that can only be instantiated once, to represent global or system-wide components, commonly used for logging, factory, platform component management, and so on. The singleton pattern seems simple and practical and difficult.
There are many ways to realize the singleton, which can be divided into two types, the lazy mode and the A Hungry man mode, and the lazy mode is relatively simple.
Public class Foosingleton { publicfinalstaticnew Foosingleton (); Private Foosingleton () {} Public void Bar () {}}
The private constructor is called only once when the building is initialized, and the JVM guarantees that it will not be called by many other threads until the class is fully initialized.
There are three ways to implement common thread safety in a hungry man mode:
- Dual detection lock mode, note that the new Foosingleton () operation in Java is actually allocated instance memory, reference to memory address, initialization instance 3 atomic operation composition. In addition to double locking, it is necessary to define the instance instance as a volatile type to prevent the command from being re-queued to ensure that it is completely correct.
- Static inner class method, the inner class is loaded only when its static methods, variables, and so on are called.
public class FooSingleton4 { private FooSingleton4 () {} public static FooSingleton4 getinstance () { return Foosingleton4holder.instance; private static class Foosingleton4holder { private
static new FooSingleton4 (); }}
- Using enumerations, according to the Java language Specification 8.9, "The final cloning method of an enum guarantees that an enumeration can never be cloned, and its special serialization mechanism guarantees that the copied object cannot be deserialized." Also, it is forbidden to instantiate an enumeration using reflection. These four aspects are guaranteed, and in addition to enumeration constants there will be no other homogeneous enumeration instances. ”
Public enum Fooenumsingleton { INSTANCE; Public Static return INSTANCE;} Public void Bar () {}}
To really implement a singleton, to prevent multiple instances from appearing, it is also considered impossible for a singleton to be cloned through the Clone method, cannot be copied by serialization deserialization, cannot be re-serialized by reflection, and so on. Now generally recommend the use of a single case, not only the code concise, relatively speaking, can better prevent the above problems.
Http://www.importnew.com/16995.html
A singleton pattern in Java