Java Singleton mode

Source: Internet
Author: User

Single Case design mode

Singleton is a pattern of creation in which a class takes Singleton mode, and when the class is created, it is possible to produce only one instance for external access and a global access point.

The core points of knowledge are as follows:

(1) The construction method of a class with a singleton design pattern is privatized (with private modification).

(2) The instantiation object of the class is generated within it and encapsulated as a private static type.

(3) Defines a static method that returns an instance of the class.

 /** * method One * Singleton mode implementation: A Hungry man type, thread safe but low efficiency */public class singletontest {
//define a private construction method private Singletontest ( {}
//Set its own instance object to a property, plus the static and final modifiers private static final singletontest instance = new Singletontest (); The
///static method returns an instance of the class public static Singletontest getinstancei () {return instance; } }

Method One is the legendary a hungry man pattern.
The advantages are: it is relatively simple to write, and there is no multithreading synchronization problem, which avoids the performance problem caused by synchronized;
The disadvantage is that when the class singletontest is loaded, the static instance is initialized, the statically variable is created and the memory space is allocated, and since then the static instance object has occupied the memory (even if you have not yet used this instance). When a class is unloaded, the static variable is destroyed and the occupied memory is freed, so memory is consumed under certain conditions.

/*** Method Two * Single-instance mode implementation: Full-Chinese, non-thread-safe **/Publicclass singletontest {

///define private construction methods (prevent passing new Singletontest () to instantiate) private Singletontest () {}
// Define a variable of type singletontest (uninitialized, note that the final keyword is not used here) private Static singletontest instance;
//Defines a static method (Singletontest is initialized when called, but may cause repeated initialization problems when accessed in multithreaded format) public static Singletontest getinstance () {if ( Instance = = null) instance = new Singletontest (); return instance;}}

Method Two is the legend of the full-Han mode
The advantage is: it is relatively simple to write, when the class singletontest is loaded, static variable instance is not created and allocated memory space, when the GetInstance method is first called, initialize the instance variable, and allocate memory, Therefore, in some specific conditions will save memory;
The disadvantage is that multiple singletontest instances are likely to occur in a concurrent environment.

/*** Method Three * Single-instance mode implementation: Full-Chinese, thread-safe simple implementation **/PublicClasssingletontest {
//Define private construction methods (prevent instantiation with new singletontest ())PrivateSingletontest () {}
// Defines a variable of type singletontest (uninitialized, note that the final keyword is not used here) private static singletontest Instance
// defines a static method (re-initializes singletontest when invoked, using synchronized Avoid multi-threaded access, which can cause heavy re-initialization problems) public static synchronized Singletontest getinstance () {if ( Instance = = null) instance = new Singletontest (); return instance;}}

Method Three is simple optimization of method two
The advantage is that multiple singletontest instances occur when using the Synchronized keyword to avoid multi-threaded access.
The disadvantage is that when synchronous methods are frequently called, the efficiency is slightly lower.

/*** Method Four * Singleton mode optimal scheme * thread safe and high efficiency **/PublicClasssingletontest {
Define a private construction methodPrivateSingletontest () {
}Defines a static private variable (uninitialized, does not use the final keyword, and volatile guarantees the visibility of the instance variable when multi-threaded access is avoided, and is called by another thread when the other variable property is not assigned when instance initialized)Privatestatic volatile singletontest instance;
//Defines a common static method that returns an instance of this type public static Singletontest getistance () {
////object instantiation (not using synchronous code block, instance not equal to NULL, return object directly, improve operational efficiency) if (instance = = null// Synchronizing code blocks (when an object is not initialized, use a synchronous block of code to guarantee that the object will not be created again after the first creation of the multi-threaded access) synchronized (Singletontest.class) {
//uninitialized, the initial instance variable if (instance = = nullnew Singletontest ();}} return instance;}}

Method Four is the best implementation of singleton pattern. Memory footprint, high efficiency, thread safety, multi-threaded operation atomicity.

(In fact, the constructor of the private type can be instantiated through the Java reflection mechanism, which essentially invalidates all Java Singleton implementations.) This post does not discuss reflection in the case of problems, default no reflection, is also a common interview has been applied scenario)

Java Singleton mode

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.