Single-instance mode in multithreaded mode (simple difference between hunger and a Hungry man mode)

Source: Internet
Author: User

Elements of the Singleton pattern:
1. private static Instance Object
2. Private constructors (guaranteed to be outside of this class, cannot create object instances by means of new)
3. Public, static, methods to access the instance object

1. A Hungry man mode:

public class Singleton1 {            private static Singleton1 singleton = new Singleton1 ();            Private Singleton1 () {                } public            static Singleton1 getinstance () {          return singleton;      
    Pros: Thread safety, absolute Singleton.Cons: When a multi-instance or other static method is used, it is loaded at startup without using it, wasting memory.

2. Lazy Mode:

public class Singleton2 {        private static Singleton2 singleton;            Private Singleton2 () {                } public            static synchronized Singleton2 getinstance () {          if (singleton = = null)               Singleton = new Singleton2 ();          return singleton;      }  }  

  Pros: Save memory when no time is used to load.

Cons: Thread is unsafe, prevents deserialization and reflection from generating new instances.

Single-instance mode in multithreaded mode (simple difference between hunger and a Hungry man 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.