Singleton - lazy man and starving Detailed formula

Belonging to create a single-mode embodiment of the schema applied to ensure that only one instance of a class the next scene, and provide a global access to its access point, such as global access point in the BeanFactory spring, the spring are all bean It is a single embodiment.

Features singletons: Starting from the system to terminate the whole process only one instance.
Singleton wording used: Formula lazy, starving type, register type, the sequence of formula.
Compare the following about the lazy man and starving type:

Lazy type: Default is not instantiated when to use and when new.

Lazy class {public
Private Lazy () {}
// default is not instantiated, when to use and when new new
Private static Lazy the lazy = null;
public static Lazy the synchronized the getInstance () {
IF (the lazy == null) {
the lazy = new new Lazy ();
}
return the lazy;
}
}
starving formula: class loading when it is instantiated, and creates a singleton object.

Hungry {class public
Private Hungry () {}
when loaded on // class instantiation, and creates a singleton object
Private new new static Final Hungry Hungry Hungry = ();
public static Hungry the getInstance () {
return Hungry;
}
}
 lazy formula and hungry Chinese-style differences:

Instantiate: the lazy man will not instantiate default, when external calls when new. When starving formula instantiated and class loading, and creates a singleton object.
Thread safety: a hungry man-style thread-safe (not appeared before the thread has been instantiated, and therefore hungry man threading must be safe). Lazy style thread safe (because lazy man's load is in the use of new instances will go, then you go to the new time is a dynamic process that is implemented into the method, such as: public static synchronized Lazy getInstance () {if (lazy == null) { lazy = new Lazy ();} if this time has a plurality of threads access to this example, this time instance does not exist, new new still, will enter into the process, on how many threads how many will be new instances. one method can only return one instance, out of which it eventually return it? is not overwrite the many examples of new? of course, this situation can be resolved, and that is to add synchronization lock, to avoid this from happening ).
Implementation of efficiency: a hungry man does not add any type of lock, so the efficiency is relatively high. Lazy man will add synchronization lock is generally used, efficiency is worse than starving formula.
Performance: a hungry man style initialized when the class is loaded, regardless of whether you use, it will instantiate, it will occupy the space, wasting memory. Lazy man when you need to instantiate when, relatively speaking, is not a waste of memory.

Guess you like

Origin www.cnblogs.com/hyhy904/p/10958554.html