Java design mode -- Singleton mode and java design mode --

Source: Internet
Author: User

Java design mode -- Singleton mode and java design mode --
The Singleton mode, as its name implies, ensures that only one instance is allowed for a class in the program. This class can create a unique instance and only provide this unique instance to the system. Generally, there are five Singleton modes: Hungry, lazy, dual lock, static internal class, and enumeration type. Among them, the hunger and lazy are the two most representative (but not the best ). First, it is a typical space-for-time mode. If the object occupies a small amount of resources, it does not need to be loaded. After all, it must be fast, you must create an instance object when loading a class. Code:

Public class SingletonDemo01 {/*** create the object when loading. The class of the hungry class * Initialization is naturally thread-safe */private static SingletonDemo01 instance = new SingletonDemo01 (); private SingletonDemo01 () {}// the method is not synchronized, and the call efficiency is high. public static SingletonDemo01 getInstance () {return instance ;}}

  

Lazy Singleton is a typical time-to-space mode. objects occupy a large amount of resources and need to be used when loading is delayed. Lazy creates instances only when needed. Code:
Public class SingletonDemo02 {/*** do not create the object when loading. The lazy * class initialization is naturally thread-safe */private static SingletonDemo02 instance; private SingletonDemo02 () {} // method synchronization, low concurrency efficiency (if not synchronized, multiple objects may be created when the concurrency is high) public static synchronized SingletonDemo02 getInstance () {if (instance = null) {instance = new SingletonDemo02 ();} return instance ;}}

  

In order to solve the problem of time and space, the dual lock Singleton can put the synchronization method in judgment, only using synchronization for the first time, and there is no need to waste time afterwards, it basically coordinates space and time. However, the underlying internal model of the JVM is occasionally faulty, so this solution is basically not recommended (this solution can be implemented using the volatile keyword or the synchronize keyword ). Code:
public class SingletonDemo03 {private static SingletonDemo03 instance=null;private SingletonDemo03(){}public static  SingletonDemo03 getInstance(){if(instance==null){SingletonDemo03 ins;synchronized (SingletonDemo03.class) {ins=instance;if(ins==null){synchronized (SingletonDemo03.class) {if(ins==null){ins=new SingletonDemo03();}}instance=ins;}}}return instance;}}

  

Static internal class Singleton is also used to solve the problem of time and space. This solution is thread-safe (all five solutions are thread-safe), with high call efficiency and delayed loading. Code:
Public class SingletonDemo04 {private SingletonDemo04 () {}// the method of loading the class is natural thread-safe private static class Singleton04ClassInStance {// There is no synchronization problem, high Efficiency private static final SingletonDemo04 instance = new SingletonDemo04 ();} // load only when calling. Delayed loading implements public static SingletonDemo04 getInstance () {return Singleton04ClassInStance. instance ;}}

  

The enumeration type Singleton Enumeration type should be an advanced version of the hungry Chinese Style. In 5, it is the most efficient, simple, secure, and efficient. However, loading cannot be delayed. The most notable feature is that the other four types can be cracked through reflection and deserialization, while the enumeration type cannot be cracked. Code:
Public enum SingletonDemo05 {/*** this enumeration element itself is a SingletonDemo05 INSTANCE */INSTANCE;/*** You can also add the operation you need */public void singletonOpt (){}}

  

Recommended Solution for five modes: if the single-instance object occupies less resources and does not require delayed loading, the enumeration method is better than the hungry one. If the single-instance object occupies more resources, the loading must be delayed, static internal class selection is better than lazy five modes:

-- Main:
① Hunger: thread security, high call efficiency, and no delay in loading
② Lazy: thread security, low call efficiency, and delayed Loading
-- Others:
③ Double lock: the cause of the underlying JVM internal model. Occasionally, problems may occur. We do not recommend that you use this lock.
④ Static internal class: thread security, high call efficiency, and delayed Loading
⑤ Enumeration: thread security, high call efficiency, and non-delayed loading. It can also prevent reflection and deserialization vulnerabilities.

For the Efficiency Comparison of the five modes, the results of 100000 calls to each thread using 10 threads are as follows: -- hungry timing: 2 ms -- lazy timing: 26 ms -- double lock timing: 3 ms -- static internal class timing: 2 ms -- enumeration timing: 1 ms more detailed code as well as reflection and deserialization to crack four Singleton mode code please refer to github: https://github.com/LiuJishuai/designPatterns

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.