Design Pattern: Singleton Pattern The Singleton Pattern ensures that only one instance of a class exists throughout the application. Common examples: Logger Database connection Cache manager Why use it? Because sometimes creating multiple objects can waste memory and cause inconsistent behavior. One object. Shared everywhere. #Java #SystemDesign #DesignPatterns #BackendDevelopment #SoftwareEngineering
Singleton Pattern: Ensures One Instance of a Class
More Relevant Posts
-
Stop wasting memory on threads that do nothing. 🛑 If you’re building Java backends, you’ve probably seen this: More users → more threads → more RAM usage I recently explored Virtual Threads (Java 21 / Project Loom), and this concept finally clicked for me. 💡 The Problem In standard Java: 1 request = 1 Platform Thread During DB/API call → thread gets blocked It’s like a waiter standing idle while food is cooking 🍽️ 👉 Wasted resources + poor scalability 🔍 The Solution: Virtual Threads 👉 Lightweight threads managed by JVM (not OS) Cheap to create Can run thousands easily Perfect for I/O-heavy backend systems ⚙️ How it actually works (Mounting / Unmounting) 1️⃣ Mounting Virtual Thread runs on a Carrier Thread (Platform Thread) 2️⃣ I/O Call (DB/API) Your code looks blocking 3️⃣ Unmounting (Parking) Virtual Thread is paused & parked in heap memory 👉 It releases the Carrier Thread 4️⃣ Carrier Thread is free Handles another request immediately 5️⃣ Remounting (Resume) Once response comes → Virtual Thread continues 💻 The "magic" in code // Looks like blocking code Runnable task = () -> { System.out.println("Processing: " + Thread.currentThread()); String data = fetchDataFromDB(); // DB/API call System.out.println("Result: " + data); }; // Run using Virtual Thread Thread.ofVirtual().start(task); 🧩 What’s happening behind the scenes? 👉 Thread.ofVirtual() Creates a lightweight thread (stored in heap, not OS-level) 👉 During DB/API call Virtual Thread gets unmounted (parked) Carrier Thread becomes free 👉 While waiting Same thread handles other requests 👉 When response comes Scheduler remounts Virtual Thread Execution continues 📈 Result No idle threads Better resource usage Simple synchronous code High scalability without complex async code 🧠 Biggest takeaway 👉 “Code looks blocking… but system is not blocked.” That’s the mindset shift. Have you tried Virtual Threads in your services yet? Did you see any real performance improvement? 🤔 #Java #BackendEngineering #VirtualThreads #ProjectLoom #Java21 #Microservices #Performance
To view or add a comment, sign in
-
-
Day 67 — LeetCode Progress (Java) Problem: Insert Delete GetRandom O(1) Goal: Design a data structure that supports: Insert Delete Get Random All in O(1) time Idea: You can’t rely on just a set or list — you need both speed + index access. Approach: Use: ArrayList → for O(1) random access HashMap → value → index mapping Insert:If value exists → return false Else: Add to list Store index in map Remove:If value not present → return false Else: Swap it with last element in list Update map for swapped element Remove last element Delete from map GetRandom:Generate random index Return element from list Time Complexity: O(1) for all operations Space Complexity: O(n) #LeetCode #DSA #Java #HashMap #ArrayList #SystemDesign #CodingJourney
To view or add a comment, sign in
-
-
Traditional Loops vs Streams in Java When working with collections, developers often face this choice 👇 Traditional Loops - Imperative approach (how to do it) - Step-by-step control - More verbose and manual Streams - Declarative approach (what to do) - Functional style (filter, map, collect) - Cleaner and more expressive code Key Insight Streams shift the focus from iteration to transformation, making code easier to read and maintain. * When to use what? - Use loops when you need fine-grained control - Use streams for cleaner, pipeline-based data processing There’s no one-size-fits-all — choose based on readability, performance, and use case. #Java #CleanCode #Streams #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
Most Java performance issues don’t show up in code reviews They show up in object lifetimes. Two pieces of code can look identical: same logic same complexity same output But behave completely differently in production. Why? Because of how long objects live. Example patterns: creating objects inside tight loops → short-lived → frequent GC holding references longer than needed → objects move to old gen caching “just in case” → memory pressure builds silently Nothing looks wrong in the code. But at runtime: GC frequency increases pause times grow latency becomes unpredictable And the worst part? 👉 It doesn’t fail immediately. 👉 It degrades slowly. This is why some systems: pass load tests work fine initially then become unstable weeks later Takeaway: In Java, performance isn’t just about what you do. It’s about how long your data stays alive while doing it. #Java #JVM #Performance #Backend #SoftwareEngineering
To view or add a comment, sign in
-
DTO (Data Transfer Object) is used to transfer only required data between client and server instead of sending the entire entity object. This improves security, performance, and clean architecture separation.. . . . . . . . . . #Java #JavaProgramming #JavaDeveloper #JavaCode #JavaScript #JavaCommunity #JavaTutorial #JavaLearning #JavaDevelopment #JavaLife #JavaLovers #JavaProjects #JavaCoding #JavaTips #JavaFramework #Java8 #JavaEE #JavaForBeginners #JavaGeek #JavaWorld #hackforge
To view or add a comment, sign in
-
🚨Microservices are powerful… but easy to misuse. 3 simple mistakes: Splitting too early → creates confusion Services depending on each other → failures spread Sharing one database → messy data & tight coupling Keep it simple first. Scale only when needed. Have you seen this happen? #Java #Microservices #BackendDeveloper
To view or add a comment, sign in
-
Spring Boot @RequestScope vs Singleton — Hidden concurrency issue ⚠️ By default: 👉 Beans are Singleton (shared across threads) But what if you store request-specific data? 🤔 ❌ Problem: Multiple users → same instance → data leakage Solution 👇 @RequestScope public class RequestData { ... } 💡 What happens: ✔ New bean per request ✔ Thread-safe data handling ⚠️ Mistake: Storing user data in Singleton beans ❌ 👉 Leads to unpredictable bugs in production Design for concurrency, not just functionality 🔥 #SpringBoot #Java #Concurrency
To view or add a comment, sign in
-
🚀 Day 7 – Exception Handling: More Than Just try-catch Today I focused on how exception handling should be used in real applications—not just syntax. try { int result = 10 / 0; } catch (Exception e) { System.out.println("Error occurred"); } This works… but is it the right approach? 🤔 👉 Catching generic "Exception" is usually a bad practice 💡 Better approach: ✔ Catch specific exceptions (like "ArithmeticException") ✔ Helps in debugging and handling issues more precisely ⚠️ Another insight: Avoid using exceptions for normal flow control Example: if (value != null) { value.process(); } 👉 is better than relying on exceptions 💡 Key takeaway: - Exceptions are for unexpected scenarios, not regular logic - Proper handling improves readability, debugging, and reliability Small changes here can make a big difference in production code. #Java #BackendDevelopment #ExceptionHandling #CleanCode #LearningInPublic
To view or add a comment, sign in
-
🚀 Solving a Critical Memory Retention Issue After Java 21 Migration Recently, I worked on resolving a critical memory retention issue in a high-throughput document processing microservice following a Java 21 & Spring Boot 3 migration. This service handles large document uploads, multipart files, and link-based document ingestion under heavy concurrent load. Post-migration, we observed abnormally high heap memory retention, increasing GC pressure and impacting runtime stability. 🔍 The Challenge • Extremely high retained heap memory under load • Increased GC pressure and latency • Memory growth proportional to concurrent requests • Heap dump analysis showed request-level observation objects as dominant GC roots 🧠 Root Cause Identified Spring Boot 3 introduced implicit Micrometer Observability instrumentation: • Security filter chain wrapped with observations • Entire HTTP request lifecycle instrumented • ~90+ objects allocated per request • No metrics backend configured — leading to memory overhead without observability benefit Under heavy traffic, these allocations accumulated and caused significant heap retention. 🛠️ Resolution Implemented • Disabled observation wrapping in Spring Security filter chain • Disabled servlet-level HTTP observation • Injected 'ObservationRegistry.NOOP' • Restored lightweight request-processing behavior 📈 Outcome ✅ Eliminated per-request observation allocations ✅ Significantly reduced heap usage & GC pressure ✅ Improved runtime stability and throughput ✅ Zero functional impact 💡 Key Takeaway Major framework upgrades can introduce implicit behavioral changes that only surface under load. This experience reinforced the importance of: • Load testing • Heap profiling • Deep root cause analysis • Performance-focused engineering Solving problems at scale like these is always rewarding — especially when they improve system stability, performance, and reliability. #Java21 #SpringBoot3 #Microservices #PerformanceEngineering #MemoryOptimization #SoftwareEngineering #BackendEngineering #Scalability #Java #SystemDesign #TechLeadership
To view or add a comment, sign in
-
The easiest way to ruin performance is to keep asking a system how it’s doing. so we don’t. We monitor system by just watching, using tools like JMH and JVM perf data, because the moment you interrupt the system, you’ve already disturbed the very behavior you wanted to measure. JMH for controlled, statistical microbenchmarks; JVM perf data accessed via tools like jcmd, jps, VisualVM, and similar utilities for low-intrusion runtime observability. A note: observability starts with understanding the data path. Every tool be it JVM-based, agents or frameworks like Spring Boot Actuator, comes with trade-offs depending on how it sources and exposes metrics. #java
To view or add a comment, sign in
-
Explore related topics
- Why Use Object-Oriented Design for Scalable Code
- How to Design Software for Testability
- How Pattern Programming Builds Foundational Coding Skills
- Maintaining Consistent Code Patterns in Projects
- Form Design Best Practices
- Consistency in UI Design Patterns
- Onboarding Flow Design Patterns
- Understanding Context-Driven Code Simplicity
- Proven Patterns for Streamlining Code Updates
- Interface Prototyping Techniques
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