Java single case

Source: Internet
Author: User

One. A hungry man mode (class loading will be instantiated, thread-safe)

1 package Com.sun.singleton; 2  3//A Hungry man Mode 4 public class Singleton {5  6     //Privatize the constructor, do not allow external direct calls create Object 7     private Singleton () {8          9     }     within//create a unique instance of a class with private static decoration (instantiated once when the class is loaded, after which the instance is invoked several times)     private static Singleton instance = new Singleton (); n     //provides an external method for obtaining an instance, using public static to modify the public static     Singleton getinstance () {15         return instance;16     } 17 18}

Two. Lazy mode (lazy, so only call method getinstance time based on the results of the decision will be instantiated, and thread is not secure)

Thread insecurity Reason: if it is a single thread that lazy mode is not a problem, but if it is multi-threaded and no lock processing is not. Instead of a, a, two threads, a thread first calls the GetInstance method, determines that instance is empty, and is about to create an instance, at which point the CPU switches to the B thread and a pauses. The b thread calls the GetInstance method to determine that instance is empty, then creates the instance, the end of the B thread after creation, and a thread to proceed, note: At this point the a thread has already judged that the instance is empty, then the instance will continue to be created, so that thread AB creates an instance of each. It is no longer a singleton mode. ------So the lazy mode to lock the synchronization.

Package com.sun.singleton;//lazy Mode (thread insecure) public class Singleton2 {        //1. Constructors are privatized and external direct calls to    private Singleton2 () are not allowed {            }        //2. Just declare the only instance of the class, when there is no real instantiation, use private static to decorate the    private static Singleton2 instance;        3. Provides a method to obtain an instance, with public static modification
(1). Resolve thread insecure-------plus sync (each thread gets an instance to determine the lock, inefficient) public static synchronized Singleton2 getinstance () { if ( instance = = null) { Return instance = new Singleton2 (); } return instance; } (2). Resolve Thread insecurity-----Double check Lock (Improve efficiency) public static Singleton2 GetInstance2 () {/ * If the first thread gets the singleton instance object, The subsequent thread does not need to enter the synchronization code block when retrieving the instance * /if (instance = = null) { synchronized (singleton2.class) { if (instance = = NULL) { instance = new Singleton2 ();}} } return instance; } }

Output:

Package Com.sun.singleton;public class Main {public    static void Main (string[] args) {                //instantiation two times for comparison test        //a Hungry man type C4/>singleton s1= singleton.getinstance ();        Singleton s2= singleton.getinstance ();        if (s1==s2) {            System.out.println ("A Hungry man is the same instance");        } else{            System.out.println ("A Hungry man type is not the same instance");        }        Lazy type        Singleton2 s3 = Singleton2.getinstance ();        Singleton2 S4 = Singleton2.getinstance ();        if (S3==S4) {            System.out.println ("Lazy is the same instance");        } else{            System.out.println ("Lazy type is not the same instance");}}}    

Results:

Description Singleton mode is the same object instantiation is a shared memory space.

The difference between the two:

A Hungry man mode: Class loading time is slow (loading time instantiation), but the runtime is faster, thread-safe.

Lazy mode: Class loading is faster, but the runtime is relatively slow (invoking the method when the instantiation), the thread is not secure.

Java single case

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.