The singleton pattern is divided into lazy and a hungry man types, the following is the comparison between the two:
1, a hungry man load immediately, when the class is loaded, an object is created for external use.
Lazy lazily loading, which creates an object only when it is called.
2, according to the above characteristics can know:
A hungry man is thread-safe, lazy-type causes access to objects is not thread-safe, you should pay attention to the use of
Synchronized keyword.
3, both have the advantages of each have a problem, lazy-type delay loading to improve efficiency, a hungry man-type thread safety.
The business tradeoff between efficiency and security
Here is an example of a cache instance that encounters an instance of the job:
The first lazy-man
1 /**2 * Players open the Carnival package3 * @author Wangchong4 * @date August 25, 2017 morning 10:51:315 */6 Public classPlayerinitialactivitycache extends Playertimeidlecache<playerinitialactivity> {7 8 Private StaticFinal Playerinitialactivitycache instance =NewPlayerinitialactivitycache ();9 Ten PrivatePlayerinitialactivitycache () { OneSupertrue, Datetimeutil.minute *Ten); A } - - Public StaticPlayerinitialactivitycache getinstance () { the returninstance; - } -}
The following a hungry man is just a demonstration of the need to temporarily change the actual use is not recommended
1 /**2 * Players open the Carnival package3 * @author Wangchong4 * @date August 25, 2017 morning 10:51:315 */6 Public classPlayerinitialactivitycache extends Playertimeidlecache<playerinitialactivity> {7 8 Private StaticPlayerinitialactivitycache instance =NULL;9 Ten PrivatePlayerinitialactivitycache () { OneSupertrue, Datetimeutil.minute *Ten); A } - - Public StaticPlayerinitialactivitycache getinstance () { the if(Instance = =NULL) { -Instance =NewPlayerinitialactivitycache (); - } - returninstance; + } -}
Rookie growth Diary: Java Fundamentals 3---singleton mode