Java Singleton mode and five eagingleton

Source: Internet
Author: User

Java Singleton mode and five eagingleton

During the interview, I often asked about the Java Singleton mode. This question can be used to evaluate the candidate's understanding of knowledge points. The Singleton mode requires that only one instance object exists during system operation.

Next, let's take a detailed analysis.Key knowledge points and five implementation methods, as well as their advantages and disadvantages.

1. The simplest method is to initialize this separate instance during class loading.

First, Defines the singleton class (without special names ):

1 public class Singleton{

Second, You need to define class variables to save the singleton object:

1 private static Singleton instance = new Singleton();

Note the following two points:

  1. Private: Except for the Singleton class, the variable cannot be accessed elsewhere;

  2. Static: Make sure it is a static class variable. In this way, the class name can be used for access without the need for an instance;

AgainYou need to explicitly define the constructor and set it to private. In this way, the compiler will report an error outside of the Singleton class, even if it is a subclass of Singleton:

1 private Singleton() {}

Last, Define the acquiring method of the singleton object,

1 public static Singleton getInstance() {2     return instance;3 }

 

Also note:

  1. Public: in this way, the external interface can be called;

  2. Static: in this way, external users can access the object through the class name; otherwise, the singleton object cannot be obtained;

Ii. Use lazy loading.On the basis of method 1, we need to modify several codes:

FirstStatic class variables should be initialized to NULL:

1 private static Singleton instance = NULL;

Second, The getInstance () method must undertake the task of generating an instance:

1 public static Singleton getInstance() {2     if(instance == NULL)3         instance = new Singleton();4     return instance;5 }

Iii. multithreading.Method 2 multiple instances may still be generated in the case of multithreading. We need to use synchronization to avoid multithreading. Use the synchronized keyword before the getInstance () method as follows:

1 public static synchronized Singleton getInstance() {

4. Consider performance issues.The synchronized keyword modifies the getInstance () method, which causes all threads that call the getInstance () method to compete for the same lock, even if the singleton object has been generated. The double check method is used here. In addition, you must note that the instance may not be NULL during initialization, which may cause program crash. Therefore, a temporary variable t is added here, make sure that the value is assigned to the instance after the initialization is complete.

public static Singleton getInstance() {    if (instance == null) {        synchronized (Singleton.class) {            if (instance == null){                Singleton t = new Singleton();                instance = t;            }        }    }    return instance;}

5. simpler methods.Based on the characteristics of static internal classes, we can use its lazy loading mechanism to simplify implementation:

1 public static Singleton getInstance(){2     return NestedClass.instance;3 }4 5 private static class NestedClass{6     private static Singleton instance = new Singleton();7 }

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.