🔍 Unlocking the Mystery of Singleton Design Pattern in Java 🚀

Rivindu Wanniachchi
unibench
Published in
2 min readMar 6, 2024
Photo by Stanislav Ivanitskiy on Unsplash

Hi guys, it’s a short one from me today!

Singleton design pattern is like the Sherlock Holmes of Java patterns 🔍. It’s always there, solving mysteries and ensuring there’s only one instance of a class lurking around. Let’s unravel the secrets of the SingletonMobile class and see how it plays its part in the Java world.

public class SingletonMobile {

private static volatile SingletonMobile instance = null;
// Private constructor to prevent instantiation from outside
private SingletonMobile() {}
// Method to get the singleton instance
public static SingletonMobile getInstance() {
if (instance == null) {
synchronized (SingletonMobile.class) {
if (instance == null) {
instance = new SingletonMobile();
}
}
}
return instance;
}
}

Let’s decode this implementation like a detective on the case:

  1. Private Constructor: The constructor is a secret passage 🕵️‍♂️ accessible only to the SingletonMobile class itself. It prevents outsiders from creating their own instances.
  2. Static getInstance() Method: This method is like the hidden treasure map 🗺 leading to the singleton instance. It guards against multiple threads trying to claim the treasure at once with double-checked locking.
  3. Lazy Initialization: The singleton instance is as elusive as a rare Pokémon 🦄, appearing only when needed. Lazy initialization keeps it hidden until it’s time to shine.
  4. Double-Checked Locking: Just like Holmes, we use our powers of deduction to ensure there’s only one instance 🎩. The double-checked locking technique keeps the bad guys (multiple instances) at bay.
  5. Volatile Keyword: We’ve added the volatile keyword to our instance variable for an extra layer of protection. It ensures that changes to the instance variable are immediately visible to all threads. Without volatile, there's a risk that different threads might see different values for the instance variable, potentially leading to the creation of multiple instances of the singleton. By using volatile, we make sure that the assignment of the singleton instance is atomic and visible across all threads.

Singleton pattern is a clever tool in the Java detective’s toolkit, but like any good mystery, it’s essential to use it wisely. Too many singletons can clutter your code like a messy crime scene 🕵️‍♀️. But when used sparingly and with precision, Singleton can help keep your application architecture neat and tidy.

So, the next time you encounter a class with a single instance, remember the Singleton pattern, the silent guardian watching over your Java code from the shadows.

Keep sleuthing, my fellow Java detectives! 🕵️‍♂️🔍

--

--