Câu hỏi phỏng vấn Java
Câu hỏi

What is an efficient way to imple...

Câu trả lời

An efficient way to implement a singleton pattern in Java is to use the Bill Pugh Singleton Implementation, also known as the Initialization-on-demand holder idiom. This approach is widely used because it combines the lazy initialization and thread-safety benefits without the need for synchronization on every call to the instance method.

Here's how the Bill Pugh Singleton Implementation works:

  1. Private Constructor: Ensure that the constructor of the singleton class is private to prevent direct instantiation by other classes.

  2. Private Inner Static Class: Define a private inner static class that contains the instance of the singleton class. This inner class is not loaded into memory until the getInstance() method is called, ensuring lazy initialization.

  3. Static Method for Instance Retrieval: Provide a public static method that returns the instance of the singleton. This method calls the inner class, which then loads and initializes the singleton instance.

Here is an example of the Bill Pugh Singleton Implementation:

java Copy
public class Singleton {
    // Private constructor
    private Singleton() {}

    // Inner static class that contains the instance of the singleton class
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    // Public static method that returns the instance of the singleton
    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

In this approach, the SingletonHolder class will not be loaded until the getInstance() method is invoked for the first time, which ensures that the instance of Singleton is created only when it is needed. Additionally, since the class initialization phase is guaranteed by the Java Language Specification to be serial, no further synchronization is necessary.

The Bill Pugh Singleton Implementation is efficient because it avoids the use of synchronized blocks in the getInstance() me...

expert

expert

Gợi ý câu hỏi phỏng vấn

junior

What are the Data Types supported by Java? What is Autoboxing and Unboxing?

junior

What is an Java Applet?

middle

What’s a deadlock?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào