Singleton mode (Java environment)

Source: Internet
Author: User

You only need to create an instance of a class in your program, using singleton mode.

Application scenario: Runtime class, database connection pool, log management (ex: LOG4J)

Implementation principle: A class, the internal definition of the static variables of the class, and defines the static method to get the static variable; the access permission of the constructor is defined as private;

A hungry man singleton mode: (Created when class is loaded)

1  Public classSingleton {2   Private StaticSingleton instance =NewSingleton ();3   PrivateSingleton () {//access rights are private to prevent an instance of the class from being fetched out of the class through a constructor function4   ...5   } 6    Public StaticSingleton getinstance () {7       returninstance;8   }     9 Ten}

Lazy Singleton mode: (created only when you need to get it)

1    Public classSingleton {2     Private StaticSingleton instance = null;3     PrivateSingleton () {//access rights are private to prevent an instance of the class from being fetched out of the class through a constructor function4      ...5     } 6      Public StaticSingleton getinstance () {
7 if (instance = = null) {
8 instance = new Singleton ();
9}
Ten returninstance;One } A -}

Lazy Singleton mode is not a problem in single-threaded, but multiple instances are created under multithreading. contrary to the original intention of the singleton model, there is a lazy singleton model with double retrieval mechanism.

Double-search mechanism of Lazy singleton mode:

1  Public classSingleton {2     Private StaticSingleton instance =NULL;3     PrivateSingleton () {4        ...;5     }6      Public StaticSingleton getinstance () {7         if(Instance = =NULL){8            synchronized(Singleton.class) {//Increase synchronization mechanism9                if(Instance = =NULL) {TenInstance =NewSingleton (); One                } A            } -         } -     } the}

Singleton mode (Java environment)

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.