Design Patterns-Singleton mode (a hungry man and lazy Java implementations)

Source: Internet
Author: User

Single-Case mode

The singleton pattern is used very often in program design, and is designed to provide a unique object in the program (guaranteed to be constructed only once), such as log objects written to the logs, implemented by Windows Task Manager (only one can be opened). This article mainly introduces the implementation of the singleton pattern using Java (including a Hungry man type and lazy type).

Realize

Using Log classes As an example, the Log object needs to have only one object in the program and initialize it only once.

A Hungry man type

A hungry man-style singleton mode is easier to understand, which is to initialize an object that needs a singleton when the singleton class loads. Implementation is also relatively easy.

publicclass Singleton{    privatestaticnew Log();    publicstaticgetInstance(){        return logObj;    }}
Lazy type

If you logObj need to take up a lot of memory, if you initialize it logObj at first, it will consume a lot of memory. At this point, some people think, if I want to use the time to initialize the object of the Log class, like the lazy, only use the time to initialize, how to design it?

Implementing a (non-thread-safe version)
publicclass Singleton{    privatestaticnull;    publicstaticgetInstance(){        ifnull){            new Log();        }        return logObj;    }}
Implementing two (thread-safe versions)
publicclass Singleton{    privatestaticnull;    publicstaticsynchronizedgetInstance(){        ifnull){            new Log();        }        return logObj;    }}

In order to achieve thread safety, this version of the implementation at the expense of a certain efficiency, if it logObj has been initialized, then other threads also need to synchronize the entry getInstance method, will cause the loss of efficiency. As a result, some people have implemented the following version.

Implement three (wrong version)
public  class  singleton  { private  static  Log logobj =    null ; public  static  Log getinstance  () {if  (logobj = = null ) {synchronized  (singleton.class) {if  (logobj = = null ) {logobj = new  Log ();    }}} return  logobj; }}

At first glance it seems that the above version is not a problem, if a thread A discovery logObj has not been initialized, then into the synchronization block initialization logObj , if there are other threads B entered, then the thread B will wait to enter the synchronization block, waiting for the A thread to exit the synchronization block, logObjhas been initialized, the B thread enters the synchronization block and discovers that it is logObj not NULL, exits the synchronization block, and is no longer initialized logObj . This allows for both thread safety and efficiency, and is indeed a clever way to encode. The problem, however, is that because of the presence of the order reordering, log is not NULL until the logobj is fully initialized. This way, other threads may get objects that are not fully initialized.

Workaround
    1. The JDK1.5 version extends the volitile semantics to ensure the correctness of the above code, so long as it is logObj declared as Volitile (Volitile only guarantees memory visibility).

    2. Use static inner classes.

When a class is loaded, its inner classes are not loaded at the same time. A class is loaded when and only if one of its static members (static domain, constructor, static method, and so on) is called.

And the JVM guarantees a thread-safe problem with class loading, so this feature can be used to write a version that balances efficiency with thread safety.

Implementation four (for both efficiency and thread-safe versions)
publicclass Singleton{    static class LogHolder{        staticnew Log();    }    publicstaticgetInstance(){        return LogHolder.logObj;    }}

This is not loaded when the class is loaded, it is Singleton LogHolder not initialized Log , and if the thread accesses getInstance the method, then the JVM will load the LogHolder class first and guarantee initialization and logObj finally return logObj .

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Design Patterns-Singleton mode (a hungry man and lazy Java implementations)

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.