Java Singleton mode (Singleton) and implementation of "reprint"

Source: Internet
Author: User
Tags instance method

I. What is a singleton mode

Because of the need of the program, sometimes we just need a class to keep an object at the same time, do not want to have more objects, at this time, we should consider the design of the singleton pattern.

Two. Characteristics of the Singleton mode

1. Singleton mode can have only one instance.

2. The Singleton class must create its own unique instance.

3. The Singleton class must provide this instance to other objects.

Three. Singleton mode vs Static Class

After knowing what a singleton pattern is, I think you will think of static classes, "Since you use only one object, why not simply use static classes?" "Here I'll compare the singleton mode with the static class.

1. The singleton can inherit and be inherited, the method can be override, and the static method can not.

2. Objects produced in a static method are freed after execution and then cleaned by the GC and do not persist in memory.

3. The static class is initialized at the first run, and the singleton pattern can have other options, which can be deferred loading.

4. Based on 2, 3, because a singleton object is often present in the DAO layer (for example, sessionfactory), if repeated initialization and release, it will occupy a lot of resources, and use singleton mode to the memory can be more resource-saving.

5. Static methods have higher access efficiency.

6. The singleton mode is easy to test.

A few misconceptions about static classes:

Myth One: Static methods reside in memory and instance methods are not.

In fact, specially written instance methods can reside in memory, while static methods require constant initialization and deallocation.

Myth Two: The static method on the heap (heap), the instance method on the stack (stack).

In fact, it is loaded into a special non-writable Code memory area.

Selection of static and Singleton pattern scenarios:

Scenario One: Do not need to maintain any state, only for global access, at this time more appropriate to use static classes.

Scenario Two: You need to maintain some specific status, which is more appropriate to use a singleton mode.

Four. Implementation of the Singleton mode

1. Lazy mode

Class Singletondemo {    staticprivatestaticif (instance==null) {instance=new return instance;}}         

As above, by providing a static object instance, the constructor of the private permission and the GetInstance () method are used to give the visitor a singleton.

The disadvantage is that, without taking into account thread safety, there may be issues where multiple visitors simultaneously access and construct multiple objects at the same time. The reason is called lazy mode, mainly because this method can be very obvious lazy loading.

For the lazy mode thread unsafe problem, we naturally think of, before the getinstance () method lock, so there is a second implementation.

2. Thread-Safe Lazy mode

Class Singletondemo {    staticprivatesynchronizedif (instance==null) {instance= Newreturn instance;}}         

However, concurrency is a special case, most of the time the lock takes up the extra resources are wasted, this patching style written out of the structure is very inefficient.

3. A Hungry man mode

Class Singletondemo {    static Singletondemo instance=newprivatestaticreturn  Instance }}

Run the class directly at the time of the loading, and then directly access. Obviously, this method does not have the effect of lazy loading, considering the aforementioned and static class comparison, this method is only more than the static Class A memory resident.

4. Static class internal loading

 public class Singletondemo {private static class singletonholder{ Private static singletondemo instance=new Singletondemo (); } private Singletondemo () {System.out.println (" Singleton has loaded "); } public static Singletondemo getinstance () {return Singletonholder.instance; }} 

The advantage of using an inner class is that the static inner class is not loaded at the time of the singleton load, but is loaded only when the getinstance () method is called, which is a thread-safe approach.

5. Enumeration methods

Enum singletondemo{    INSTANCE;    void othermethods () {        System.out.println ("Something");}}   

The way that effective Java author Josh Bloch advocated, seems to me to be a form of God. Resolves the following three issues:

(1) Free serialization.

(2) guarantee only one instance.

(3) Thread safety.

If we want to invoke its method, only the following actions are required:

Class Hello {    void main (string[] args) {SingletonDemo.INSTANCE.otherMethods ();}}  

This beauty-filled code really has ended all the other implementations.

6. Double check Lock method

PublicClassSingletondemo {Private volatileStaticsingletondemo instance; private Singletondemo () {System.out.println ("Singleton Has loaded "); } public static Singletondemo getinstance () {if (Instance==nullsynchronized (Singletondemo. Class) {if (Instance== Null) {Instance=new Singletondemo (); }}} return instance;}}      

Next I'll explain what the double-check lock method will look like when concurrency occurs:

STEP 1. Thread A accesses the getinstance () method because the singleton is not instantiated, so it enters the locking block.

STEP 2. Thread B accesses the getinstance () method because the singleton has not been instantiated to access the next block of code, and the next block of code has been locked by thread 1.

STEP 3. Thread A enters the next judgment, because the singleton is not instantiated, so a singleton instantiation, the successful instantiation of the exit code block, unlocked.

STEP 4. Thread B enters the next block of code, locks the thread, and goes to the next judgment because it has been instantiated, exits the code block, and unlocks.

STEP 5. Thread A gets the singleton instance and returns, and thread B does not get the singleton and returns NULL.

In theory, double-check lock method is thread-safe, and this method realizes lazyloading.

Java Singleton mode (Singleton) and implementation of "reprint"

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.