Java Singleton mode

Source: Internet
Author: User

Singleton mode ensures that only one instance of a class exists.

In a computer system, the driver objects of the thread pool, cache, log Object, dialog box, printer, and video card are often designed as singleton.

A hungry man method

publicclassSingleton {  

     private static Singleton = new Singleton();      private Singleton() {}      public static getSignleton(){          return singleton;      } }A hungry man in the creation of a class at the same time has created a static object for the system to use, no longer change, so it is inherently thread-safe. However, you cannot defer creating objects. Lazy Type public class Singleton {      private static Singleton singleton = null ;      private Singleton(){}      public static Singleton getSingleton() {          if (singleton == null ) singleton = new Singleton();          return singleton;      } }Lazy Singleton class. Instantiate yourself at the first call, without regard to thread safety, which is thread insecure public class Singleton {          private Singleton(){}               public static Singleton getSingleton(){          return Holder.singleton;      }       private static class Holder {          private static Singleton singleton =  new Singleton();      } } through static internal classes, delayed loading, and thread-safe (this avoids the creation of static instances when the Singleton class is loaded, and because static inner classes are only loaded once, this is also thread-safe:) Enumeration Notation
 Public enum enumsingleton{
INSTANCE;
}
Access via Enumsingleton test=enumsingleton.instance
The use of enumerations, in addition to thread-safe and anti-reflection forced invocation of the constructor, also provides an automatic serialization mechanism to prevent deserialization when a new object is created. Therefore, effective Java recommends using enumerations as much as possible to implement the singleton.

Java 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.