About singleton patterns in Java

Source: Internet
Author: User

A. Features:

① Singleton class can have only one instance

② Singleton classes must create their own unique instances themselves

③ Singleton class must provide this instance to all other objects

Two. Implementation method:

① a hungry man type

public class singleton1{Private Singleton1 ();    private static Singleton1 single=new Singleton1 ();    public static final Singleton1 getinstance () {return single; } }

② Lazy 1 (thread insecure)

public class singleton1{Private Singleton1 ();    private static Singleton1 Single=null;         public static Singleton1 getinstance () {if (single==null) {single=new Singleton1 ();     } return single; } }

This approach is because no lock is added to the GetInstance method, and it produces multiple Singleton1 instances when multiple threads are accessing the method at the same time.

③ Lazy 2 (thread-safe, but inefficient, that is, adding a thread lock [the place where the lock is a waste of time, if you can reduce the determination of the lock can save time])

public class singleton1{Private Singleton1 ();    private static Singleton1 Single=null;         public static synchronized Singleton1 getinstance () {if (single==null) {single=new Singleton1 ();     } return single; } }

④ Lazy 3 (thread-safe, high-efficiency, double-judge)

  public class singleton1{    private singleton1 ();     private static singleton1 single=null;    public static  singleton1 getinstance () {        if (single==null) {             synchronized (Singleton1.class) {                     if (Single==null) {                         s=new singleton1 ();                      }              }               }         return single;      } }

About singleton patterns in Java

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.