🚀 Singleton Design Pattern in Java – With Complete Code & Explanation Today I solved a HackerRank challenge on the Singleton Pattern — a very important concept in object-oriented design. 🎯 What is Singleton? 👉 Ensures that a class has only one instance and provides a global access point to it. 🛠️ Complete Code with Line-by-Line Explanation: import java.util.Scanner; import java.lang.reflect.*; // Singleton class class Singleton { // Step 1: Create a single static instance of the class public static final Singleton singleton = new Singleton(); // Step 2: Public variable to store string public String str; // Step 3: Private constructor (prevents object creation from outside) private Singleton() { } // Step 4: Public method to return the single instance public static Singleton getSingleInstance() { return singleton; } } // Main class public class Main { public static void main(String args[]) throws Exception { // Scanner to take input Scanner sc = new Scanner(System.in); // Step 5: Get the same instance twice Singleton s1 = Singleton.getSingleInstance(); // first reference Singleton s2 = Singleton.getSingleInstance(); // second reference // Step 6: Check both references point to same object assert (s1 == s2); // true means Singleton works // Step 7: Verify constructor is private using Reflection Class c = s1.getClass(); Constructor[] allConstructors = c.getDeclaredConstructors(); assert allConstructors.length == 1; for (Constructor ctor : allConstructors) { // Modifier 2 = private if (ctor.getModifiers() != 2 || !ctor.toString().equals("private Singleton()")) { System.out.println("Wrong class!"); } } // Step 8: Take input string String str = sc.nextLine(); // Step 9: Assign value to singleton object s1.str = str; s2.str = str; // both refer to same object // Step 10: Print output System.out.println("Hello I am a singleton! Let me say " + str + " to you"); } } 💡 Key Takeaways: ✔ Only one object is created ✔ Constructor is private ✔ Access through static method ✔ Memory efficient & widely used 🔥 Where is it used? 👉 Logging systems 👉 Configuration management 👉 Database connections #Java #DesignPatterns #SingletonPattern #OOP #HackerRank #CodingPractice #JavaDeveloper #LearningJourney
Singleton Design Pattern in Java with Code & Explanation
More Relevant Posts
-
🔹 Singleton Design Pattern in Java — A Practical Overview The Singleton pattern is one of the most fundamental design patterns in Java, widely used in real-world applications for managing shared resources. 🔹 What is Singleton? The Singleton pattern ensures: • Only one instance of a class is created • A global access point is provided to that instance 🔹 Common Use Cases • Database connection management • Logging frameworks • Application configuration • Caching mechanisms 🔹 Basic Implementation (Lazy Initialization) public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } 🔹 Limitation This implementation is not thread-safe. In a multi-threaded environment, multiple instances may be created. 🔹 Thread-Safe Implementation public class Singleton { private static volatile Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } 🔹 Recommended Approach Bill Pugh Singleton (Inner Static Class) public class Singleton { private Singleton() {} private static class Holder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return Holder.INSTANCE; } } Advantages: • Thread-safe without synchronization overhead • Lazy initialization • Clean and maintainable implementation 🔹 Alternative (Robust Approach) public enum Singleton { INSTANCE; } Advantages: • Inherently thread-safe • Handles serialization • Prevents reflection-based instantiation 🔹 Key Takeaways • Prefer Bill Pugh Singleton for most scenarios • Use Enum Singleton for maximum robustness • Always consider thread-safety in concurrent applications #Java #DesignPatterns #BackendDevelopment #SystemDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
Take a deep dive into capturing snapshots and using them to diagnose bugs in a Java application using the Lightrun agent and plugin:
To view or add a comment, sign in
-
🚀🎊Day 72 of 90 – Java Backend Development ✨🎆 In the world of Java multithreading, a Mutex (short for Mutual Exclusion) is a synchronization mechanism used to ensure that only one thread can access a specific resource or block of code at a time. Think of it like a bathroom key at a coffee shop: only the person holding the key can enter; everyone else has to wait in line until the key is returned. 👉 How Mutex works in Java? Java doesn’t have a class literally named Mutex. Instead, it provides several tools that implement mutex behavior to prevent race conditions (where two threads try to modify the same data simultaneously, leading to bugs). 👉 1. The synchronized Keyword This is the simplest way to achieve mutual exclusion. When a thread enters a synchronized block, it acquires an "intrinsic lock" (or monitor) on the object. No other thread can enter any synchronized block on that same object until the first thread finishes. public synchronized void increment() { // Only one thread can execute this at a time count++; } 👉 2. ReentrantLock Found in the java.util.concurrent.locks package, this is a more flexible, explicit version of a mutex. It offers features that synchronized doesn't, such as: i) Timed waiting: Trying to get the lock for a specific amount of time. ii) Interruptible locks: Allowing a thread to back out if it's waiting for a lock. iii) Fairness: Ensuring the longest-waiting thread gets the lock next. 👉 Why use a Mutex? Without a mutex, you encounter the "Lost Update" problem. For example, if two threads try to increment a variable count = 5 at the exact same time: i) Thread A reads 5. ii) Thread B reads 5. iii) Thread A hits 6 and saves it. iv) Thread B hits 6 and saves it. Result: The count is 6, even though two increments happened. It should be 7. A Mutex forces these operations to happen one after the other, ensuring data integrity. #Multithreading #Mutex #ReentrantLock #synchronized
To view or add a comment, sign in
-
-
🚀 CyclicBarrier in Java — Small Concept, Powerful Synchronization In multithreading, coordination between threads is critical ⚡ 👉 CyclicBarrier allows multiple threads to wait for each other at a common point before continuing — ensuring everything stays in sync 🔥 💡 Think of it like a checkpoint 🏁 No thread moves forward until all have arrived! 🌍 Real-Time Example Imagine a report generation system 📊 Multiple threads fetch data from different APIs 📡 Each processes its own data ⚙️ Final report should generate only when all threads finish 👉 With CyclicBarrier, you ensure: ✅ All threads complete before aggregation ✅ No partial or inconsistent data ✅ Smooth parallel execution 💻 Quick Code Example import java.util.concurrent.CyclicBarrier; public class Demo { public static void main(String[] args) { CyclicBarrier barrier = new CyclicBarrier(3, () -> System.out.println("All threads reached. Generating final report...")); Runnable task = () -> { try { System.out.println(Thread.currentThread().getName() + " fetching data..."); Thread.sleep(1000); barrier.await(); System.out.println(Thread.currentThread().getName() + " done!"); } catch (Exception e) { e.printStackTrace(); } }; for (int i = 0; i < 3; i++) new Thread(task).start(); } } 💪 Why it’s powerful ✔️ Keeps threads perfectly synchronized ✔️ Prevents incomplete execution ❌ ✔️ Reusable for multiple phases ♻️ 🔥 Final Thought 👉 It’s a small but powerful feature — use it wisely based on your project needs to ensure the right level of synchronization without overcomplicating your design. #Java #Multithreading #Concurrency #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
💻 Exception Handling in Java — Write Robust Code 🚀 Handling errors properly is what separates basic code from production-ready applications. This visual breaks down Exception Handling in Java in a simple yet technical way 👇 🧠 What is an Exception? An exception is an unexpected event that occurs during program execution and disrupts the normal flow. 👉 Example: Division by zero → ArithmeticException 🔍 Exception Hierarchy: Object ↳ Throwable ↳ Error (System-level, not recoverable) ↳ Exception (Can be handled) ✔ Checked Exceptions (Compile-time) ✔ Unchecked Exceptions (Runtime) ⚡ Types of Exceptions: ✔ Checked → Must be handled (IOException, SQLException) ✔ Unchecked → Runtime errors (NullPointerException, ArrayIndexOutOfBoundsException) 🔄 Try-Catch-Finally Flow: 1️⃣ try → Code that may cause exception 2️⃣ catch → Handle the exception 3️⃣ finally → Always executes (cleanup resources) 🛠 Throw vs Throws: throw → Explicitly throw an exception throws → Declare exceptions in method signature 🧪 Custom Exceptions: Create your own exceptions for business logic validation → improves readability & control ⚠️ Common Exceptions: ArithmeticException NullPointerException ArrayIndexOutOfBoundsException IOException 🔥 Best Practices: ✔ Handle specific exceptions (avoid generic catch) ✔ Use meaningful error messages ✔ Always release resources (finally / try-with-resources) ✔ Don’t ignore exceptions silently ✔ Use custom exceptions where needed 🎯 Key takeaway: Exception handling is not just about avoiding crashes — it’s about building reliable, maintainable, and user-friendly applications. #Java #ExceptionHandling #Programming #SoftwareEngineering #BackendDevelopment #Coding #Learning
To view or add a comment, sign in
-
-
The Command Pattern in Java: Eliminating Fat Service Classes with Commands and Handlers Fat Service classes are a liability — one class that does everything is a class that's impossible to test and dangerous to change. This post shows how to apply the Command pattern in Java using Records, Repository interfaces, and single-responsibility Handlers to keep your business logic clean and isolated....
To view or add a comment, sign in
-
The Command Pattern in Java: Eliminating Fat Service Classes with Commands and Handlers Fat Service classes are a liability — one class that does everything is a class that's impossible to test and dangerous to change. This post shows how to apply the Command pattern in Java using Records, Repository interfaces, and single-responsibility Handlers to keep your business logic clean and isolated....
To view or add a comment, sign in
-
🚀 Java 25 Innovation Alert: Compact Object Headers (COH)!🚀 If you’re working with large-scale Java applications, this JVM feature is a game-changer you might not know about — but it silently makes your apps faster, leaner, and more efficient. Let me break it down 👇 ✨ What are Compact Object Headers? In Java, every object has a little metadata block called the object header — storing info like: 🧠 Object hash codes 🗂️ Garbage Collection (GC) data 🔐 Lock states for synchronization 📚 Class metadata pointers Traditionally, these headers can take 16 to 24 bytes each on a 64-bit JVM — and when you have millions (or billions!) of objects, memory usage quickly balloons. 🔧 Java 25 to the rescue! With Compact Object Headers, the JVM compresses these metadata pieces: Mark Word (GC info, locks, hash) gets squeezed into fewer bytes Klass Pointer (class info) uses half the space Rare flags move out of the header into auxiliary space 💡 The result? Object headers shrink to ~8–12 bytes on average. 🔥 Why this matters: 🏋️ Save gigabytes of memory in large applications ⚡ Boost CPU cache locality & speed up access 🧹 Lower GC overhead, improving pause times and throughput 💻 Free up heap space for your actual data and logic ⚙️ How to enable COH in Java 25: By default, if your heap is under 32GB and compressed pointers (OOPs) are enabled, COH kicks in automatically. You can manually turn it on with: -XX:+UseCompactObjectHeaders Check it with: java -XX:+PrintFlagsFinal -version | grep CompressedOops ✅ Takeaway: You don’t have to change your code—this JVM-level magic makes your Java apps more memory-efficient and performant right out of the box. If you’re architecting Java systems at scale, COH is a subtle but powerful tool in your toolbox. #Java #JVM #Performance #MemoryManagement #Java25 #TechTips #SoftwareEngineering #Programming
To view or add a comment, sign in
-
-
🚀 Java 25 Innovation Alert: Compact Object Headers (COH)! 🚀 If you’re working with large-scale Java applications, this JVM feature is a game-changer you might not know about — but it silently makes your apps faster, leaner, and more efficient. Let me break it down👇 ✨ What are Compact Object Headers? In Java, every object has a little metadata block called the object header — storing info like: 🧠 Object hash codes 🗂️ Garbage Collection (GC) data 🔐 Lock states for synchronization 📚 Class metadata pointers Traditionally, these headers can take 16 to 24 bytes each on a 64-bit JVM — and when you have millions (or billions!) of objects, memory usage quickly balloons. 🔧 Java 25 to the rescue! With Compact Object Headers, the JVM compresses these metadata pieces: Mark Word (GC info, locks, hash) gets squeezed into fewer bytes Class Pointer (class info) uses half the space Rare flags move out of the header into auxiliary space 💡 The result? Object headers shrink to ~8–12 bytes on average. 🔥 Why this matters: 🏋️ Save gigabytes of memory in large applications ⚡ Boost CPU cache locality & speed up access 🧹 Lower GC overhead, improving pause times and throughput 💻 Free up heap space for your actual data and logic ⚙️ How to enable COH in Java 25: By default, if your heap is under 32GB and compressed pointers (OOPs) are enabled, COH kicks in automatically. You can manually turn it on with: -XX:+UseCompactObjectHeaders Check it with: java -XX:+PrintFlagsFinal -version | grep CompressedOops ✅ Takeaway: You don’t have to change your code—this JVM-level magic makes your Java apps more memory-efficient and performant right out of the box. If you’re architecting Java systems at scale, COH is a subtle but powerful tool in your toolbox. #Java #JVM #Performance #MemoryManagement #Java25 #TechTips #SoftwareEngineering #Programming
To view or add a comment, sign in
-
-
🚀🎊Day 84 of 90 – Java Backend Development ✨🎆 In Java, the final keyword is a non-access modifier used to restrict the user from changing the state of a variable, method, or class. Think of it as a way to achieve immutability and prevent inheritance or overriding. 👉 1. Final variables: When you declare a variable as final, its value cannot be modified once it has been initialized. It essentially becomes a constant. i) Local Variables: Must be initialized before use and cannot be reassigned. ii) Instance Variables: Can be initialized during declaration or inside the constructor. iii) Static Variables: Often used to create "Class Constants" (e.g., public static final double PI = 3.14159;). Note: For objects, final means the reference cannot change. You can still modify the internal state (fields) of the object, but you cannot point the variable to a new object. 👉2. Final methods: A method declared with the final keyword cannot be overridden by subclasses. i) Usage: Use this when you want to ensure that the specific implementation of a method remains consistent across all subclasses. ii) Performance: Historically, the compiler could optimize final methods through inlining, though modern JVMs often do this automatically regardless. 👉 3. Final classes: A class declared as final cannot be subclassed (inherited). i) Security & Integrity: Many standard Java library classes are final, such as String, Integer, and other wrapper classes. This prevents developers from creating a "fake" version of a String that might behave maliciously. ii) Implicitly Final: If a class is final, all of its methods are implicitly final as well. 👉 Code example: final class Vehicle { // Cannot be inherited final int SPEED_LIMIT = 90; // Constant final void drive() { // Cannot be overridden System.out.println("Driving at " + SPEED_LIMIT); } } #FinalKeyword #Immutable #Performance #Java #Constant
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development