What is an efficient way to imple...
What is an efficient way to imple...
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:
Private Constructor: Ensure that the constructor of the singleton class is private to prevent direct instantiation by other classes.
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.
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:
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
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào