Thread safety issues in Singleton mode

Source: Internet
Author: User

The singleton mode means that there can be only one object in the system for a class, and it is impossible to come up with a second one.

1. Singleton mode - a Hungry man (thread-safe, no synchronization mechanism required)

public class Singleton {private static Singleton instance=new Singleton ();    Initializes an instance object directly to the private Singleton () {    ///private type constructor to ensure that other class objects cannot be directly new to an instance of the object} public static Singleton  GetInstance () {    //The only public method of this class is       return instance; }}

One drawback of the above code is that when the class is loaded, it is directly new to a static object, and when there are more such classes in the system, the startup speed slows down. Now the popular design is to say "lazy loading", we can initialize the first class object at the first use.

2. Singleton mode - lazy (thread insecure, using synchronous method )

public class Singleton {      private static Singleton instance;  
Private Singleton () {
} synchronized Singleton getinstance () { //Synchronize the method that gets the instance if (instance = = null) instance = new Singleton (); return instance; }
}

One of the above code locks a method, the granularity is a bit large, the improvement is only locked in the new statement is OK.

3. Singleton mode - lazy (thread insecure, use synchronous code block )

public class Singleton {         private static Singleton instance;         Private Singleton () {      } public          static Singleton getinstance () {    //Synchronize the method that gets the instance         if (instance = = null) {             synchronized (singleton.class) {                 if (instance = = null)                     instance = new Singleton ();}        }        return instance;      }        }

Thread safety issues in 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.