CH-04 : The Singleton Paradox — Jai & Veeru vs. The Multiverse of Objects

Jai and Veeru were sipping chai on their terrace when Veeru suddenly blurted out, “Jai, our app has a problem!” Jai, halfway through a biscuit, raised an eyebrow. “What now? Did you time-travel and forget your phone again?” Veeru shook his head. “Worse. Our app is creating too many objects! The memory usage is skyrocketing!” Jai sighed. “Ah, the Singleton problem. We need only one instance of an object, but Java keeps making more, wasting resources.” Veeru scratched his head. “So how do we fix it?” Jai leaned forward, a mischievous smile forming. “We use Java 21’s Record Patterns & Sealed Classes!” Veeru blinked. “Sounds fancy. Explain.” The Problem: Too Many Instances Veeru had written this code for a Logger class: public class Logger { public Logger() { System.out.println("New Logger Created!"); } } And every time he called new Logger(), it created a new instance! Veeru frowned. “But I only need one logger. Not a thousand!” Jai smirked. “That’s where Singleton Pattern comes in!” The Fix: Singleton with Sealed Classes Jai rewrote the Logger class using Java 21’s Sealed Classes: public sealed class Logger permits OnlyOne { private Logger() {} // Private Constructor private static final Logger instance = new Logger(); public static Logger getInstance() { return instance; } } final class OnlyOne extends Logger {} // Prevents more instances Veeru’s eyes widened. “Wait… so now, even if someone tries to extend Logger, Java won’t allow it?" Jai nodded. “Yes! Sealed classes restrict inheritance, enforcing one true instance!" Veeru clapped his hands. “Jai, you’re a genius!” Record Patterns: The New Magic Trick Veeru frowned again. “Okay, Singleton is solved. But what if we have too many duplicate objects, like users logging in with the same details?” Jai chuckled. “That’s where Record Patterns help. Instead of manually checking fields, Java 21 does it for us!” Instead of writing this old, tedious way: record User(String name, String role) {} User u = new User("Veeru", "Admin"); if (u.name().equals("Veeru") && u.role().equals("Admin")) { System.out.println("Welcome, Admin!"); } Jai showed the modern approach: record User(String name, String role) {} static void checkUser(User u) { if (u instanceof User("Veeru", "Admin")) { System.out.println("Welcome, Admin!"); } } Veeru was stunned. “That’s so much cleaner! No more repetitive .equals() calls?" Jai grinned. “Yup! Java 21 makes code smarter and easier to read.” The Real Paradox… Just as Jai and Veeru were celebrating their victory, Veeru’s phone beeped. It was an error message from their server. “Warning: Multiple instances detected. Memory overload imminent!” Veeru gulped. “Jai… didn’t we just fix this?” Jai stared at the screen, confused. “Yes… which means something — or someone — is breaking the Singleton rule…” They exchanged a nervous glance. “Could it be… a rogue object?” Veeru whispered. Jai’s eyes narrowed. “Only one way to find out.”

May 18, 2025 - 02:00
 0
CH-04 : The Singleton Paradox — Jai & Veeru vs. The Multiverse of Objects

Jai and Veeru were sipping chai on their terrace when Veeru suddenly blurted out, “Jai, our app has a problem!”

Jai, halfway through a biscuit, raised an eyebrow. “What now? Did you time-travel and forget your phone again?”

Veeru shook his head. “Worse. Our app is creating too many objects! The memory usage is skyrocketing!”

Jai sighed. “Ah, the Singleton problem. We need only one instance of an object, but Java keeps making more, wasting resources.”

Veeru scratched his head. “So how do we fix it?”

Jai leaned forward, a mischievous smile forming. “We use Java 21’s Record Patterns & Sealed Classes!”

Veeru blinked. “Sounds fancy. Explain.”

The Problem: Too Many Instances

Veeru had written this code for a Logger class:

public class Logger {
    public Logger() { System.out.println("New Logger Created!"); }
}

And every time he called new Logger(), it created a new instance!

Veeru frowned. “But I only need one logger. Not a thousand!”

Jai smirked. “That’s where Singleton Pattern comes in!”

The Fix: Singleton with Sealed Classes

Jai rewrote the Logger class using Java 21’s Sealed Classes:

public sealed class Logger permits OnlyOne {
    private Logger() {} // Private Constructor  
    private static final Logger instance = new Logger();
    public static Logger getInstance() { return instance; }
}

final class OnlyOne extends Logger {} // Prevents more instances

Veeru’s eyes widened. “Wait… so now, even if someone tries to extend Logger, Java won’t allow it?"

Jai nodded. “Yes! Sealed classes restrict inheritance, enforcing one true instance!"

Veeru clapped his hands. “Jai, you’re a genius!”

Record Patterns: The New Magic Trick

Veeru frowned again. “Okay, Singleton is solved. But what if we have too many duplicate objects, like users logging in with the same details?”

Jai chuckled. “That’s where Record Patterns help. Instead of manually checking fields, Java 21 does it for us!”

Instead of writing this old, tedious way:

record User(String name, String role) {}

User u = new User("Veeru", "Admin");
if (u.name().equals("Veeru") && u.role().equals("Admin")) {
    System.out.println("Welcome, Admin!");
}

Jai showed the modern approach:

record User(String name, String role) {}

static void checkUser(User u) {
    if (u instanceof User("Veeru", "Admin")) {
        System.out.println("Welcome, Admin!");
    }
}

Veeru was stunned. “That’s so much cleaner! No more repetitive .equals() calls?"

Jai grinned. “Yup! Java 21 makes code smarter and easier to read.”

The Real Paradox…

Just as Jai and Veeru were celebrating their victory, Veeru’s phone beeped. It was an error message from their server.

“Warning: Multiple instances detected. Memory overload imminent!”

Veeru gulped. “Jai… didn’t we just fix this?”

Jai stared at the screen, confused. “Yes… which means something — or someone — is breaking the Singleton rule…”

They exchanged a nervous glance.

“Could it be… a rogue object?” Veeru whispered.

Jai’s eyes narrowed. “Only one way to find out.”