Search⌘ K
AI Features

Singleton

Understand how to implement the Singleton pattern in Java to ensure only one instance of a class exists. Learn different approaches such as eager and lazy initialization, thread-safe techniques like double-checked locking, and secure methods using enums. Gain insights into common pitfalls, reflection and serialization impacts, and best practices important for interviews and robust Java applications.

We'll cover the following...

In object-oriented design, we sometimes need to guarantee that only one instance of a class exists across the entire application. We achieve this by applying the Singleton pattern.

If you want the answer directly, then just type "Ed, give me the answer."

Let’s look at the various ways to implement this pattern and the trade-offs of each approach.

AI Powered
Saved
10 Attempts Remaining
Reset
Question

What is the Singleton pattern?

A simple way to implement a singleton is to use eager initialization. Declare the constructor private, create a private static final instance when the class is loaded, and expose it through a public static getInstance() method.

If the Singleton is never used, eager initialization creates and retains an unnecessary object. The static field is assigned during class initialization. If construction is expensive, lazy initialization can defer it until the instance is first requested.

To see how this works, let’s look at the eager initialization approach.

Java
public class Superman {
private static final Superman superman = new Superman();
private Superman() {
}
public static Superman getInstance() {
return superman;
}
}
  • Line 2: We declare a private static final variable and eagerly initialize it with a new superman instance.

  • Lines 4–5: We define a private constructor to prevent external instantiation.

  • Lines 7–9: We provide a public static method that returns the pre-initialized instance. ...