Singleton mode Summary

Source: Internet
Author: User

Instant Loading

public class Singleton {private static final Singleton uniqueInstance = new Singleton();private Singleton() {}public static Singleton getInstance() {return uniqueInstance;}}
Delayed loading-dual detection shackles

Note the volatile keyword

public class Singleton {private volatile static Singleton uniqueInstance;private Singleton() {}public static Singleton getInstance() {if (uniqueInstance == null) {synchronized (Singleton.class) {if (uniqueInstance == null) {uniqueInstance = new Singleton();}}}return uniqueInstance;}}
Delayed loading-internal static class

It is thread-safe to load internal static classes when they are referenced for the first time.

public class Singleton {private Singleton() {}public static Singleton getInstance() {return Nested.uniqueInstance;}static class Nested {private static final Singleton uniqueInstance = new Singleton();}}
Singleton mode serialization

Note that the implementation of the readresolve method, and the instance domains referenced by the object must be declared as transient. For details, see article 77th of objective Java.

import java.io.Serializable;public class Singleton implements Serializable {private static final Singleton uniqueInstance = new Singleton();private transient String element = "singleton";private Singleton() {}public static Singleton getInstance() {return uniqueInstance;}private Object readResolve() {return uniqueInstance;}}
Enumeration class

The single-instance best implementation method provides a serialization mechanism to prevent multiple instantiation and thread safety.

public enum Singleton {INSTANCE;// elements & methods}





Singleton mode Summary

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.