Singleton
Learn how to implement the Singleton pattern in Java to ensure a single instance across an application. Understand eager and lazy initialization, thread-safe methods like double-checked locking, and the Bill Pugh Singleton approach. Discover how enums provide a secure Singleton implementation and consider how reflection and serialization can affect Singleton integrity.
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.
Let’s look at the various ways to implement this pattern and the trade-offs of each approach.
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.
Line 2: We declare a private static final variable and eagerly initialize it with a new
supermaninstance.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.
A variant of the same approach is to initialize the instance inside a static block. This ...