Note singleton five wording

Hungry Chinese-style: when it is initialized class loader

Disadvantages: If this class has never been used, resulting in a waste of resources

Its variants have static code block the way, but still advantages and disadvantages of the same type and hungry man

 

 

 

Lazy type: initialized when the call to get an instance method

Advantages: implements lazy loading

Disadvantages: can only be used in single-threaded

Its variants have improved double-check, where you must use double-check, if there is no second layer inspection or when there will be more than one instance of (a thread two threads simultaneously by the first re-examination, the two threads have to instantiate of, but can not remove the first, or else waiting to get a large number of threads is determined)

 

double-check:

 

 

 

There is still a problem: to understand the three steps at a new object, which the second and third step of the order is likely to be reversed or performed simultaneously, so there will need to use the following questions :( volatile applied to the object, to prevent this occurs reordered)

 

 

 

 

Static inner class type:

The difference between starving style is that this time will not immediately initialize class loading, but then instantiated when you call the acquisition method, and the use of their properties jvm multi-thread safe

 

 

 

 

Method static inner class and type are double checked better implementation, but they can not prevent deserialized (or reflected), to generate a plurality of instances, damage to a single embodiment, then look at the enumerated wording

 

An enumerated :( uncommon but highly recommend)

When there jvm predetermined sequence of enumeration, only the output object to the name attribute enumeration result, when the deserialized by the valueOf java.lang.Enum () to find the object by name, rather than Create a new object. Reflection being given directly if the enumerated classes, so to ensure there will be no single case of a breach of

 

If there is work in the global information class and the working class and other stateless scene when the recommended wording enumeration to achieve Singleton pattern, "Efficient Java" book had also recommended such an approach

 

Guess you like

Origin www.cnblogs.com/shineipangtuo/p/12395991.html