Design Mode: Three creation modes of Singleton mode and their respective advantages and disadvantages

Source: Internet
Author: User

Design Mode: Three creation modes of Singleton mode and their respective advantages and disadvantages

Singleton mode: ensures that a class has only one instance and provides global access points. The implementation of Singleton mode in Java requires a private constructor, a static method, and a static variable. Determine the performance and resource restrictions, and how to select an appropriate solution to implement Singleton to solve the problem of multithreading. If multiple class loaders are used, a single instance may become invalid and multiple instances may be generated. The double check lock does not apply to java 1.4 or earlier versions.

 

Method 1:

 

Package singleton;/*** synchronous getInstance () method: * a bit: Ensure thread security. * Disadvantage: the performance is greatly reduced * @ author Arvon **/public class Singleton1 {private static Singleton1 instance; private Singleton1 () {} public static synchronized Singleton1 getInstance () {if (instance = null) instance = new Singleton1 (); return instance ;}}


 

 

Method 2:

 

Package singleton;/*** "eager" to create an instance * advantages: thread security * disadvantages: increase the burden of Program Creation and running * @ author Arvon **/public class Singleton2 {private static Singleton2 instance = new Singleton2 (); private Singleton2 () {} public static Singleton2 getInstance () {return instance ;}}


 

Method 3:

 

Package singleton;/*** double check lock * @ author Administrator **/public class Singleton3 {private volatile static Singleton3 instance; private Singleton3 () {} public static Singleton3 getInstance () {if (instance = null) synchronized (Singleton3.class) {// only enters the synchronization block for the first time if (instance = null) instance = new Singleton3 ();} return instance ;}}


 

 

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.