Singleton pattern
The Singleton Pattern is one of the simplest design patterns in Java. This type of design pattern belongs to the creational patterns, and it provides the best way to create objects.
This pattern involves a single class that is responsible for creating its own object while ensuring that only a single object is created. This class provides a way to access its unique object, which can be accessed directly without instantiating the class.
The Singleton Pattern is a creational design pattern that ensures a class has only one instance and provides a global access point to that instance.
Note:
- 1. The singleton class can have only one instance.
- 2. The singleton class must create its own unique instance.
- 3. The singleton class must provide this instance to all other objects.
Summary
Singleton pattern (Singleton Pattern)
Intent
Ensure that a class has only one instance and provide a global access point to that instance.
Main problem solved
The problem of frequently creating and destroying globally used class instances.
When to use it
When you need to control the number of instances and save system resources.
How to solve
Check whether the singleton already exists in the system; if it exists, return that instance; if not, create a new instance.
Key code
The constructor is private.
Application Example
- A class has only one class teacher.
- When operating on files in a multi-process and multi-threaded environment, Windows avoids multiple processes or threads operating on the same file at the same time by handling it through a unique instance.
- The device manager is designed as a Singleton; for example, if a computer has two printers, it avoids printing the same file at the same time.
Advantages
- Only one instance in memory, reducing memory overhead, especially when instances are frequently created and destroyed (such as managing the homepage page cache of an academy).
- Avoid multiple occupations of resources (such as file writing operations).
Disadvantages
- No interface, cannot be inherited.
- Conflicts with the Single Responsibility Principle: a class should only care about its internal logic, not about how it is instantiated.
Use Cases
- Generate unique serial numbers.
- Counters in WEB, to avoid incrementing the count in the database on every refresh, cache it first.
- Creating objects that consume too many resources, such as I/O and database connections.
Notes
- Thread Safety:
getInstance()synchronized locks need to be used in the methodsynchronized (Singleton.class)to prevent multiple threads from entering at the same time and causing the instance to be created multiple times. - Lazy initialization: The instance is created the first time the
getInstance()method is called. - Serialization and deserialization: Override the
readResolvemethod to ensure that no new instance is created during deserialization. - Reflection attacks: Add protective code in the constructor to prevent creating new instances through reflection.
- Class loader issues: Note that complex class loading environments may cause multiple instance problems.
structures
The Singleton Pattern contains the following main roles:
- Singleton class: The class that contains the singleton instance, usually declaring the constructor as private.
- Static member variable: The static member variable used to store the singleton instance.
- Get instance method: A static method used to obtain the singleton instance.
- Private constructor: Prevents external direct instantiation of the singleton class.
- Thread-safety handling: Ensures that the creation of the singleton instance is safe in a multi-threaded environment.
Create a class that implements
We will create a SingleObject class.SingleObject The class has its private constructor and a static instance of itself.
SingleObject The class provides a static method for the outside world to obtain its static instance.SingletonPatternDemo Class uses SingleObject class to get the SingleObject object.

Step 1
Create a Singleton class.
SingleObject.java
public
class
SingleObject
{
//
Create an object of SingleObject
private
static
SingleObject
instance
=
new
SingleObject
(
)
;
//
Make the constructor private so that the class cannot be instantiated
private
SingleObject
(
)
{
}
//
Get the only available object
public
static
SingleObject
getInstance
(
)
{
return
instance
;
}
public
void
showMessage
(
)
{
System
.
out
.
println
(
"
Hello World!
"
)
;
}
}
Step 2
Get the unique object from the singleton class.
SingletonPatternDemo.java
public
class
SingletonPatternDemo
{
public
static
void
main
(
String
[
]
args
)
{
//
Illegal constructor
//
Compile-time error: The constructor SingleObject() is not visible
//
SingleObject object = new SingleObject();
//
Get the only available object
SingleObject
object
=
SingleObject
.
getInstance
(
)
;
//
Display message
object
.
showMessage
(
)
;
}
}
Step 3
Run the program, output result:
Hello World!
Several implementation methods of the Singleton Pattern
There are various ways to implement the Singleton Pattern, as follows:
1. Lazy initialization, thread-unsafe
**Lazy initialization:** Yes
**Multi-thread safe:** No
**Implementation difficulty:** Easy
**Description:** This is the most basic implementation. The biggest problem with this implementation is that it does not support multi-threading. Because there is no synchronized lock, strictly speaking it is not a Singleton Pattern.
This approach has obvious lazy loading and does not require thread safety; it cannot work properly in multi-threading.
Example
public
class
Singleton
{
private
static
Singleton
instance
;
private
Singleton
(
)
{
}
public
static
Singleton
getInstance
(
)
{
if
(
instance
==
null
)
{
instance
=
new
Singleton
(
)
;
}
return
instance
;
}
}
The several implementation methods introduced next all support multi-threading, but differ in performance.
2. Lazy initialization, thread-safe
**Lazy initialization:** Yes
**Multi-thread safe:** Yes
**Implementation difficulty:** Easy
**Description:** This approach has good lazy loading and works well in multi-threading, but efficiency is very low, and synchronization is not needed in 99% of cases.
Advantage: It is initialized only on the first call, avoiding memory waste.
Disadvantage: The synchronized lock must be added to guarantee a singleton, but locking affects efficiency.
The performance of getInstance() is not critical to the application (this method is not used frequently).
Example
public
class
Singleton
{
private
static
Singleton
instance
;
private
Singleton
(
)
{
}
public
static
synchronized
Singleton
getInstance
(
)
{
if
(
instance
==
null
)
{
instance
=
new
Singleton
(
)
;
}
return
instance
;
}
}
3. Eager initialization
**Lazy initialization:** No
**Multi-thread safe:** Yes
**Implementation difficulty:** Easy
**Description:** This approach is relatively common, but it tends to produce garbage objects.
Advantage: No locking, so execution efficiency is improved.
Disadvantage: It is initialized when the class is loaded, wasting memory.
It avoids multi-threading synchronization issues based on the classloader mechanism. However, the instance is instantiated when the class is loaded. Although there are many reasons for class loading, in the Singleton Pattern most are calls to the getInstance method, but it cannot be determined whether other methods (or other static methods) cause class loading. In that case, initializing the instance obviously does not achieve the effect of lazy loading.
Example
public
class
Singleton
{
private
static
Singleton
instance
=
new
Singleton
(
)
;
private
Singleton
(
)
{
}
public
static
Singleton
getInstance
(
)
{
return
instance
;
}
}
4. Double-checked locking (DCL, i.e., double-checked locking)
**JDK version:** From JDK1.5 onward
**Lazy initialization:** Yes
**Multi-thread safe:** Yes
**Implementation difficulty:** Relatively complex
**Description:** This approach uses a double-lock mechanism, which is safe and maintains high performance in multi-threading.
The performance of getInstance() is critical to the application.
Example
public
class
Singleton
{
private
volatile
static
Singleton
singleton
;
private
Singleton
(
)
{
}
public
static
Singleton
getSingleton
(
)
{
if
(
singleton
==
null
)
{
synchronized
(
Singleton
.
class
)
{
if
(
singleton
==
null
)
{
singleton
=
new
Singleton
(
)
;
}
}
}
return
singleton
;
}
}
5. Registration / static inner class
**Lazy initialization:** Yes
**Multi-thread safe:** Yes
**Implementation difficulty:** Average
**Description:** This approach achieves the same effect as double-checked locking but is simpler to implement. For lazy initialization of static fields, this approach should be used instead of double-checked locking. This approach only applies to static fields; double-checked locking can be used when instance fields need lazy initialization.
This approach also uses the classloader mechanism to ensure that only one thread is involved when initializing the instance. It differs from the third approach in that: in the third approach, as long as the Singleton class is loaded, the instance is instantiated (failing to achieve the lazy loading effect), whereas in this approach, even if the Singleton class is loaded, the instance is not necessarily initialized. Because the SingletonHolder class is not actively used, only when the getInstance method is explicitly called will the SingletonHolder class be explicitly loaded, thereby instantiating the instance. Imagine that if instantiating the instance consumes a lot of resources, you want to delay its loading; on the other hand, you do not want it to be instantiated when the Singleton class is loaded, because you cannot ensure that the Singleton class may not be actively used and thus loaded elsewhere. In that case, instantiating the instance is obviously inappropriate. At this point, this approach appears very reasonable compared to the third approach.
Example
public
class
Singleton
{
private
static
class
SingletonHolder
{
private
static
final
Singleton
INSTANCE
=
new
Singleton
(
)
;
}
private
Singleton
(
)
{
}
public
static
final
Singleton
getInstance
(
)
{
return
SingletonHolder
.
INSTANCE
;
}
}
6. Enum
**JDK version:** From JDK1.5 onward
**Lazy initialization:** No
**Multi-thread safe:** Yes
**Implementation difficulty:** Easy
**Description:** This implementation has not been widely adopted, but it is the best way to implement the Singleton Pattern. It is more concise, automatically supports the serialization mechanism, and absolutely prevents multiple instantiations.
This approach is advocated by Josh Bloch, author of Effective Java. It not only avoids multi-threading synchronization issues, but also automatically supports the serialization mechanism, preventing deserialization from recreating new objects and absolutely preventing multiple instantiations. However, because the enum feature was only added after JDK1.5, writing code this way may feel unfamiliar, and in practical work it is rarely used.
Private constructors cannot be invoked through a reflection attack.
Example
public
enum
Singleton
{
INSTANCE
;
public
void
whateverMethod
(
)
{
}
}
**Advice from experience:** In general, the first and second lazy initialization approaches are not recommended; the third eager initialization approach is recommended. The fifth registration approach is used only when the lazy loading effect is explicitly required. If deserialization creates objects, you can try the sixth enum approach. If there are other special requirements, you can consider using the fourth double-checked locking approach.