🚀 One of the Most Complex Java Problems Asked in Top Tech Interviews 💡 Design a Thread-Safe LRU Cache with O(1) Operations --- 🧠 Problem Statement: Design and implement an LRU (Least Recently Used) Cache with the following operations: - "get(key)" → Returns value if present, else -1 - "put(key, value)" → Insert/update the value ⚡ Constraints: - Both operations must run in O(1) time - Must be thread-safe (handle concurrent access properly) --- 🔥 Why this is challenging? This problem tests: - Data Structures (HashMap + Doubly Linked List) - Concurrency (Locks, synchronization) - Real-world system design (cache eviction strategy) --- 🛠️ Approach: To achieve O(1): - Use a HashMap → Fast lookup - Use a Doubly Linked List → Maintain LRU order For Thread Safety: - Use ReentrantLock (better than synchronized for flexibility) --- 💻 Java Implementation: import java.util.*; import java.util.concurrent.locks.ReentrantLock; class LRUCache { class Node { int key, value; Node prev, next; Node(int k, int v) { key = k; value = v; } } private final int capacity; private Map<Integer, Node> map; private Node head, tail; private ReentrantLock lock = new ReentrantLock(); public LRUCache(int capacity) { this.capacity = capacity; this.map = new HashMap<>(); head = new Node(0, 0); tail = new Node(0, 0); head.next = tail; tail.prev = head; } public int get(int key) { lock.lock(); try { if (!map.containsKey(key)) return -1; Node node = map.get(key); remove(node); insert(node); return node.value; } finally { lock.unlock(); } } public void put(int key, int value) { lock.lock(); try { if (map.containsKey(key)) { remove(map.get(key)); } if (map.size() == capacity) { Node lru = tail.prev; remove(lru); map.remove(lru.key); } Node newNode = new Node(key, value); insert(newNode); map.put(key, newNode); } finally { lock.unlock(); } } private void remove(Node node) { node.prev.next = node.next; node.next.prev = node.prev; } private void insert(Node node) { node.next = head.next; node.prev = head; head.next.prev = node; head.next = node; } } --- ⚠️ Common Mistakes: - Forgetting to update order after "get()" - Not handling concurrency → leads to race conditions - Using only HashMap (misses LRU behavior) --- 📈 Follow-up Questions Asked in Interviews: - Can you make it lock-free? - How would you scale this in distributed systems? - What if capacity is millions? #Java #SystemDesign #CodingInterview #Concurrency #TechCareers
Design a Thread-Safe LRU Cache with O(1) Operations in Java
More Relevant Posts
-
🚀 Top 5 Tough Java Questions Asked in GCC Interviews (2026) — With Answers Cracking GCC companies today is not about syntax… it’s about how you think, design, and scale systems. Here are 5 real tough Java questions trending in interviews 👇 --- 1️⃣ Explain Java Memory Model (JMM) & Happens-Before Relationship 💡 Why they ask: Tests deep concurrency understanding ✅ Answer: - JMM defines how threads interact through memory (heap, stack) - Happens-before ensures visibility + ordering guarantees - Example: - Write to variable → happens-before → another thread reads it - Without it → race conditions / stale data 👉 Key point: "volatile", "synchronized", locks enforce happens-before --- 2️⃣ How would you design a thread-safe Singleton in Java? 💡 Why they ask: Tests design + concurrency ✅ Answer (Best approach): public class Singleton { private Singleton() {} private static class Holder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return Holder.INSTANCE; } } ✔ Lazy loaded ✔ Thread-safe ✔ No synchronization overhead --- 3️⃣ HashMap Internals – What happens during collision? 💡 Why they ask: Tests core + performance thinking ✅ Answer: - Uses array + linked list / tree (Java 8+) - Collision → same bucket index - Java 8: - LinkedList → converts to Red-Black Tree after threshold - Improves from O(n) → O(log n) 👉 Key: Good "hashCode()" + "equals()" matters --- 4️⃣ Difference between "synchronized", "ReentrantLock", and "volatile" 💡 Why they ask: Real-world concurrency decisions ✅ Answer: Feature| synchronized| ReentrantLock| volatile Locking| Yes| Yes (flexible)| No Fairness| No| Yes (optional)| No Interruptible| No| Yes| No Visibility| Yes| Yes| Yes 👉 Use: - "volatile" → visibility only - "synchronized" → simple locking - "ReentrantLock" → advanced control --- 5️⃣ How would you design a scalable REST API using Spring Boot? 💡 Why they ask: System design + real work ✅ Answer: - Use layered architecture (Controller → Service → Repository) - Apply: - Caching (Redis) - Async processing ("CompletableFuture") - Circuit breaker (Resilience4j) - Ensure: - Idempotency - Rate limiting - Proper exception handling 👉 Bonus: Use microservices + event-driven design --- 🔥 Pro Tip: In 2026, interviews focus on: - JVM internals - Concurrency - System design - Real production scenarios --- 💬 Which question surprised you the most? ♻️ Save this for your next interview prep! Do comment and like for more reach!!! #Java #GCC #InterviewPrep #Backend #SpringBoot #SoftwareEngineering
To view or add a comment, sign in
-
🚨 Java Memory Model (JMM) — One Interview Question That Separates Average Developers from Strong Engineers If you attend enough Java interviews, one topic will almost always appear: Java Memory Model (JMM). Many developers know multithreading… Some know synchronized… But very few truly understand how memory behaves inside the JVM. And that is exactly what the Java Memory Model defines. Let’s break it down from zero to advanced level in simple English. ⸻ 🔷 What is Java Memory Model? The Java Memory Model (JMM) defines how threads interact with memory in Java. In simple words, it answers three critical questions: ◆ How variables are stored in memory ◆ How multiple threads access them ◆ How changes made by one thread become visible to another thread Without JMM, multithreaded programs would behave randomly and unpredictably. ⸻ 🔷 The Two Main Memory Areas When a Java program runs, memory is mainly divided into two logical parts. 🟦 Heap Memory (Shared Memory) • All objects live here • Shared by all threads 🟩 Thread Stack (Local Memory) • Each thread has its own stack • Stores method calls and local variables Important point: 👉 Threads do not directly work on heap variables all the time. They often work with local copies of variables inside their own thread memory. This is where many concurrency problems begin. ⸻ 🔷 The Core Problem JMM Solves Imagine two threads: Thread A updates a variable. Thread B reads the same variable. But Thread B may still see the old value. Why? Because the updated value may still be in Thread A’s local cache and not yet written back to main memory. So without rules, threads may see different values of the same variable. JMM defines rules to control this behavior. ⸻ 🔷 The Happens-Before Rule This is the most important concept in JMM. The Happens-Before relationship guarantees that: ✔ Changes made by one thread ✔ Become visible to another thread ✔ In a predictable order Example cases where Happens-Before is guaranteed: ◆ Thread start() ◆ Thread join() ◆ Entering and exiting synchronized blocks ◆ Writing and reading volatile variables These rules ensure memory visibility and ordering. ⸻ 🔷 Important JMM Keywords ⚡ synchronized • Creates a memory barrier • Forces threads to read/write from main memory • Ensures visibility and mutual exclusion ⚡ volatile • Guarantees visibility but not atomicity • Changes are immediately visible to other threads ⚡ final • Ensures object state is visible correctly after construction ⸻ 🔷 Why JMM Is Important in Real Systems Without understanding JMM, developers often create bugs like: ❌ Race conditions ❌ Stale data problems ❌ Instruction reordering issues ❌ Invisible updates between threads These bugs are extremely hard to debug in production systems. #Java #JavaMemoryModel #JVM #Multithreading #Concurrency #SoftwareArchitecture #BackendDevelopment #SystemDesign #JavaDevelopers #TechLeadership
To view or add a comment, sign in
-
-
I didn't like JAVA Until.. I found this Java Ultimate Resources Sheet 0. Complete Interview prep for Java Backend Engineer - https://lnkd.in/dTvYVutD 1. Java Basics: - Data types, keywords, variables, operators, loops: https://lnkd.in/dr8fYigm - String: https://lnkd.in/dA2nn79A - Array: https://lnkd.in/dMDTpPm2 2. Java OOPs: - abstraction, encapsulation, inheritance, polymorphism: https://lnkd.in/djNeVRex - Constructor: https://lnkd.in/d_W6Dd8D 3. Java Collections: - Map, Queue, List, Set: https://lnkd.in/dJPdQhXK - https://lnkd.in/dtdQsFgj 4. JVM architecture: - https://lnkd.in/dEEAasFa 5. Java Memory Model: - https://lnkd.in/dV_WAEHr - https://lnkd.in/dADTTYJG - https://lnkd.in/dr8XmbrD - https://lnkd.in/d7nkrKii 6. Garbage Collections: - https://lnkd.in/d--bgKvK 7. Exception Handling: - https://lnkd.in/d7pgMRCJ - https://lnkd.in/dE7MCH8j 8. Generics: - https://lnkd.in/dwD7Bzss - https://lnkd.in/d9Bb9fb7 9. Serialization: - https://lnkd.in/dGm2mjwy - https://lnkd.in/dFNepNW9 10. Reflection API: - https://lnkd.in/dBXdHSD7 - https://lnkd.in/dXsfPWUp 11. File Handling: - https://lnkd.in/d8g8f45b - https://lnkd.in/dyCwzkhp 12. Java Functional Programming: - https://lnkd.in/dPk5vszt - https://lnkd.in/dVzpUvXn - https://lnkd.in/d_7pzZuh - https://lnkd.in/dS9x8SnA 13. Java multi-threading: - https://lnkd.in/ddKr9rgz - https://lnkd.in/d6uFXkce - https://lnkd.in/dK32XAuV - https://lnkd.in/dP39ZYgT 14. Java Regex: - https://lnkd.in/dRJf5nX4 15. Java 8 Features: - https://lnkd.in/dMqx4dve - https://lnkd.in/dfFkbkmc 16. Java All Remaining Features: - https://lnkd.in/dSc6MqfA - https://lnkd.in/drMWeGKw 𝗞𝗲𝗲𝗽𝗶𝗻𝗴 𝘁𝗵𝗶𝘀 𝗶𝗻 𝗺𝗶𝗻𝗱, 𝗜 𝘄𝗲𝗻𝘁 𝗱𝗲𝗲𝗽 𝗮𝗻𝗱 𝗱𝗼𝗰𝘂𝗺𝗲𝗻𝘁𝗲𝗱 𝗲𝘃𝗲𝗿𝘆𝘁𝗵𝗶𝗻𝗴 𝗶𝗻𝘁𝗼 𝗮 𝗝𝗮𝘃𝗮 𝗕𝗮𝗰𝗸𝗲𝗻𝗱 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿 𝗚𝘂𝗶𝗱𝗲. 𝗚𝗲𝘁 𝘁𝗵𝗲 𝗴𝘂𝗶𝗱𝗲 𝗵𝗲𝗿𝗲: https://lnkd.in/dfhsJKMj keep learning, keep sharing ! #java #backend #javaresources
To view or add a comment, sign in
-
I didn't like JAVA Until.. I found this Java Ultimate Resources Sheet 0. Complete Interview prep for Java Backend Engineer - https://lnkd.in/dTvYVutD 1. Java Basics: - Data types, keywords, variables, operators, loops: https://lnkd.in/dr8fYigm - String: https://lnkd.in/dA2nn79A - Array: https://lnkd.in/dMDTpPm2 2. Java OOPs: - abstraction, encapsulation, inheritance, polymorphism: https://lnkd.in/djNeVRex - Constructor: https://lnkd.in/d_W6Dd8D 3. Java Collections: - Map, Queue, List, Set: https://lnkd.in/dJPdQhXK - https://lnkd.in/dtdQsFgj 4. JVM architecture: - https://lnkd.in/dEEAasFa 5. Java Memory Model: - https://lnkd.in/dV_WAEHr - https://lnkd.in/dADTTYJG - https://lnkd.in/dr8XmbrD - https://lnkd.in/d7nkrKii 6. Garbage Collections: - https://lnkd.in/d--bgKvK 7. Exception Handling: - https://lnkd.in/d7pgMRCJ - https://lnkd.in/dE7MCH8j 8. Generics: - https://lnkd.in/dwD7Bzss - https://lnkd.in/d9Bb9fb7 9. Serialization: - https://lnkd.in/dGm2mjwy - https://lnkd.in/dFNepNW9 10. Reflection API: - https://lnkd.in/dBXdHSD7 - https://lnkd.in/dXsfPWUp 11. File Handling: - https://lnkd.in/d8g8f45b - https://lnkd.in/dyCwzkhp 12. Java Functional Programming: - https://lnkd.in/dPk5vszt - https://lnkd.in/dVzpUvXn - https://lnkd.in/d_7pzZuh - https://lnkd.in/dS9x8SnA 13. Java multi-threading: - https://lnkd.in/ddKr9rgz - https://lnkd.in/d6uFXkce - https://lnkd.in/dK32XAuV - https://lnkd.in/dP39ZYgT 14. Java Regex: - https://lnkd.in/dRJf5nX4 15. Java 8 Features: - https://lnkd.in/dMqx4dve - https://lnkd.in/dfFkbkmc 16. Java All Remaining Features: - https://lnkd.in/dSc6MqfA - https://lnkd.in/drMWeGKw 𝗞𝗲𝗲𝗽𝗶𝗻𝗴 𝘁𝗵𝗶𝘀 𝗶𝗻 𝗺𝗶𝗻𝗱, 𝗜 𝘄𝗲𝗻𝘁 𝗱𝗲𝗲𝗽 𝗮𝗻𝗱 𝗱𝗼𝗰𝘂𝗺𝗲𝗻𝘁𝗲𝗱 𝗲𝘃𝗲𝗿𝘆𝘁𝗵𝗶𝗻𝗴 𝗶𝗻𝘁𝗼 𝗮 𝗝𝗮𝘃𝗮 𝗕𝗮𝗰𝗸𝗲𝗻𝗱 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿 𝗚𝘂𝗶𝗱𝗲. 𝗚𝗲𝘁 𝘁𝗵𝗲 𝗚𝘂𝗶𝗱𝗲 𝗵𝗲𝗿𝗲: https://lnkd.in/dTvYVutD Use SDE20 to get 20% off. Stay Hungry, Stay FoolisH!
To view or add a comment, sign in
-
Stop writing Java Switch statements like it’s 2004! If you are still writing switch statements with break; at the end of every line, you are living in the past! Java has transformed the humble switch from a clunky branching tool into a powerful, functional expression. Here is the evolution of how we control logic in Java: 1️⃣ The "Classic" Era (Java 1.0 - 6) * Syntax: case X: ... break; * Limitation: Only primitives (int, char) and Enums. * The Risk: "Fall-through" bugs. Forget one break and your logic cascades into chaos. 2️⃣ The "Modern Expression" (Java 14) Java 14 turned the Switch into an Expression. It can now return a value! * Arrow Syntax (->): No more break. It’s cleaner and safer. * Assignment: var result = switch(val) { ... }; * Yield: Use yield to return values from complex multi-line blocks. 3️⃣ The "Pattern Matching" Powerhouse (Java 21) This is the game changer. Switch is no longer just for values; it’s for Types. * Case Patterns: Switch directly on an Object. * Automatic Casting: No more instanceof followed by manual casting. * Guarded Patterns: Use the when keyword to add logic filters directly into the case. * Null Safety: Explicitly handle case null without crashing. Sample : /** * SCENARIO: Processing a result object that could be * a String, an Integer, or a custom Status record. */ // 🛑 THE OLD WAY (Java 8) - Verbose and manual public String handleResultOld(Object result) { if (result == null) { return "Unknown"; } if (result instanceof String) { String s = (String) result; // Manual casting return "Message: " + s; } else if (result instanceof Integer) { Integer i = (Integer) result; return "Code: " + i; } return "Unsupported"; } // ✅ THE MODERN WAY (Java 21) - Concise and Type-Safe public String handleResultModern(Object result) { return switch (result) { case null -> "Unknown"; case String s when s.isBlank() -> "Empty Message"; case String s -> "Message: " + s; // Automatic casting case Integer i -> "Code: " + i; default -> "Unsupported"; }; } #Java21 #ModernJava #BackendDevelopment #Coding #TechCommunity #Developers #LearningToCode
To view or add a comment, sign in
-
🚀 Java Strings — Part 3: Immutability You’ve heard it a hundred times: 👉 “Strings are immutable in Java” But interviews don’t stop there… they go deeper: 👉 Why? How? What actually happens internally? Let’s break it down 👇 --- ### 🔹 What does “Immutable” really mean? 👉 Once a String object is created, its value cannot be changed java String s = "Hello"; s.concat(" World"); System.out.println(s); // Hello ❗ The original object is untouched --- ### 🔹 What actually happens in memory? java String s = "Hello"; s = s.concat(" World"); 👉 Step-by-step: 1. "Hello" created in SCP 2. "Hello World" created as a new object 3. Reference s now points to new object 💡 Old object is still there (eligible for GC later) --- ### 🔹 Internal Structure (Very Important 🔥) In Java, String is backed by: java private final byte[] value; 👉 Key points: - final → reference cannot change - No setter methods → cannot modify content 💡 That’s what enforces immutability --- ### 🔹 Why Immutability is Needed? #### ✅ 1. Security - Used in: - DB URLs - File paths - Network connections 👉 Prevents accidental/malicious changes --- #### ✅ 2. Thread Safety - No synchronization needed - Multiple threads can share same String safely --- #### ✅ 3. Performance (String Pool 🔥) - Reuse of objects in SCP - Saves memory --- #### ✅ 4. Caching (HashCode) java String s = "abc"; s.hashCode(); // cached internally 👉 Hashcode is calculated once and reused --- ### 🔹 Interview Trap Questions ⚠️ ⚠️ Q1: Is String really immutable? 👉 Yes (value is immutable) 👉 But reference can change java String s = "Hello"; s = "World"; // new object --- ⚠️ Q2: Can we break immutability? (Advanced) 👉 Yes, using Reflection (not recommended) java // Modifying internal value via reflection (hacky) 💡 This is why immutability is “by design”, not absolute enforcement --- ⚠️ Q3: Why StringBuilder is mutable but String is not? 👉 String → safety + caching 👉 StringBuilder → performance (fast modifications) --- ### 🔹 Common Mistakes Developers Make ❌ Assuming concat() modifies original String ❌ Using String in loops (performance issue) ❌ Not understanding memory impact --- ### 🔥 Real Interview Insight 👉 If interviewer asks “Why String is immutable?” Don’t just say definition ❌ Say this instead ✅: ✔ Security ✔ Thread safety ✔ Performance via String Pool ✔ Hashcode caching --- ### 🔥 Final Takeaway ✔ String immutability = design decision ✔ Every modification → new object ✔ Core reason behind many Java optimizations ✔ Frequently asked in interviews (with twists!) #Java #SDET #AutomationTesting #JavaInterview #Immutability #Programming #TechLearn
To view or add a comment, sign in
-
🚀 Java Wrapper Classes: Hidden Behaviors That Trip Up Even Senior Developers Most developers know wrapper classes. Very few understand what happens under the hood — and that’s exactly where top companies separate candidates. Here’s a deep dive into the concepts that actually matter 1. Integer Caching Integer a = 4010; Integer b = 4010; System.out.println(a == b); // false Integer c = 127; Integer d = 127; System.out.println(c == d); // true Q.Why? Java caches Integer values in the range -128 to 127. Inside range → same object (cached) Outside range → new object (heap) 💡 Pro Insight: You can even extend this range using: -XX:AutoBoxCacheMax=<size> 2. == vs .equals() — Silent Bug Generator System.out.println(a == b); // false → reference comparison System.out.println(a.equals(b)); // true → value comparison Using == with wrapper objects is one of the most common production bugs. Rule: == → checks memory reference .equals() → checks actual value 3. hashCode() vs identityHashCode() System.out.println(a.hashCode()); System.out.println(System.identityHashCode(a)); Two objects can have: Same value → same hashCode() Different memory → different identityHashCode() 4. Silent Overflow in Primitive Conversion Integer a = 4010; byte k = a.byteValue(); // -86 What actually happens: byte range = -128 to 127 4010 % 256 = 170 170 interpreted as signed → -86 No error. No warning. This is how real-world bugs sneak into systems. 5. Powerful Utility Methods (Underrated) Integer.toBinaryString(4010); Integer.toHexString(4010); Integer.bitCount(4010); Integer.numberOfLeadingZeros(4010); Useful in: Bit manipulation Competitive programming Low-level optimization 6. Character & Boolean — Also Cached Boolean b1 = true; Boolean b2 = true; System.out.println(b1 == b2); // true Boolean → fully cached Character → cached in ASCII range 7. Character Utilities = Clean Code Character.isLetter('a'); Character.isDigit('3'); Character.isWhitespace('\t'); Character.toUpperCase('a'); The Big Picture Wrapper classes are NOT just primitives with methods. They reveal how Java handles: Memory optimization Object identity Autoboxing behavior Performance trade-offs A big thanks to my mentors Syed Zabi Ulla, peers, and the amazing developer community Oracle for continuously pushing me to go beyond basics and truly understand concepts at a deeper level. #Java #JVM #CoreJava #CodingInterview #FAANG #SoftwareEngineering #BackendDevelopment #ProgrammingTips
To view or add a comment, sign in
-
-
💡 Functional Interfaces in Java — Beyond the Basics If you think Functional Interfaces are just about Lambda expressions, you're only scratching the surface. Let’s go deeper 👇 🔹 Recap: What is a Functional Interface? An interface with exactly one abstract method, annotated optionally with "@FunctionalInterface" for clarity and compile-time safety. --- 🔹 Key Characteristics ✔ Can have multiple default and static methods ✔ Enables functional programming style in Java ✔ Works seamlessly with lambda expressions and method references --- 🔹 Custom Functional Interface Example @FunctionalInterface interface Calculator { int operate(int a, int b); } Usage: Calculator add = (a, b) -> a + b; System.out.println(add.operate(5, 3)); // 8 --- 🔹 Lambda vs Method Reference Lambda: (a, b) -> a + b Method Reference: Integer::sum 👉 Cleaner and more reusable when method already exists. --- 🔹 Where are Functional Interfaces Used? 🔥 1. Streams API list.stream() .filter(x -> x > 10) // Predicate .map(x -> x * 2) // Function .forEach(System.out::println); // Consumer 🔥 2. Multithreading new Thread(() -> System.out.println("Running thread")).start(); 🔥 3. Event Handling & Callbacks Used heavily in asynchronous and reactive programming. --- 🔹 Types of Functional Interfaces (Deep View) ✨ Predicate<T> → Boolean conditions Used for filtering data ✨ Function<T, R> → Transformation Convert one form of data to another ✨ Consumer<T> → Performs action Logging, printing, updating ✨ Supplier<T> → Generates data Lazy loading, object creation ✨ BiFunction / BiPredicate → Work with 2 inputs --- 🔹 Why Companies Care? (Interview Insight) ✔ Reduces boilerplate code ✔ Encourages clean architecture ✔ Essential for Spring Boot & Microservices ✔ Frequently used in real-world production code --- 🔹 Common Mistakes to Avoid ❌ Adding more than one abstract method ❌ Ignoring built-in functional interfaces ❌ Overusing lambdas (readability matters!) --- 🔹 Pro Tip for Freshers 🚀 When solving DSA or backend problems, try rewriting logic using: 👉 Lambda expressions 👉 Streams 👉 Built-in functional interfaces This shows modern Java proficiency in interviews. --- 💬 Final Thought: Functional Interfaces are not just a feature—they represent a shift in how Java developers think and write code. Master them, and your code becomes shorter, smarter, and more powerful ⚡ #Java #FunctionalProgramming #Java8 #BackendDeveloper #CodingJourney #SoftwareEngineering #InterviewPrep
To view or add a comment, sign in
-
💡 What is Java Heap Space and OutOfMemoryError (and how to avoid it) ? 1️⃣ What is Java Heap Space ❓ Java heap space refers to a section of memory used by the Java Virtual Machine (JVM) for runtime memory allocation of Java objects. When a Java application creates a new object, that object is always allocated in the heap space 2️⃣ What is OutOfMemoryError ❓ This error occurs when the Java application attempts to allocate a new object in the heap, but there is insufficient memory available. This can happen mainly due to: 1. Memory Leaks: Objects are no longer needed but are still referenced, preventing the garbage collector from reclaiming their memory 2. Excessive Object Creation: The application creates too many objects, consuming all available heap space. 3. Insufficient Heap Size: The default or configured maximum heap size (-Xmx JVM argument) is too small for the application's memory requirements. 3️⃣ How to avoid OutOfMemoryError ❓ 1. Know your application's max heap size. This is the limit after which the error occurs. Run the below command by placing your java application's process ID:- jcmd <process_id> VM.flags | findstr MaxHeapSize Sample output:- -XX:CICompilerCount=2 .... -XX:MaxHeapSize=1610612736 ..... The above sample output shows 1.6 GB of max heap size for a program. 2. Use Memory Profiler tools like VisualVM to check in real-time, if your app's memory usage is nearing the max heap size or not. 4️⃣ How to solve OutOfMemoryError ❓ 1. By using memory profiler tools like VisualVM:- 1.1. Identify Memory Leaks for analyzing object creation and heap dumps to identify objects that are unnecessarily retained and fix the underlying code issues. 1.2. Identify Excessive Object Creation and optimize it by reducing the number of objects created or their size if possible. 2. Increase Heap Size: The most common immediate solution is to increase the maximum heap size using the -Xmx JVM argument during running your java app, for example, -Xmx512m for 512 MB. Note: This should be the last resort as the default max heap size should be enough in most of the cases and the error should be solved by removing memory leaks and optimizing object creation as explained before. #JavaPerformance #Backend #Microservices #SoftwareArchitecture #TechSolutions #PerformanceOptimization #Programming #Software #SystemDesign #Java #IT #SpringBoot #Error #SoftwareEngineering
To view or add a comment, sign in
-
One of the TOUGHEST scenario questions asked in a Java Backend interview Question: "Your payment service is processing 10,000 transactions per second. Suddenly response time jumps from 20ms to 8 seconds. No errors in logs. No alerts fired. Business is losing money every second. How do you debug this?" This question separates tutorial developers from production engineers. STAR Framework Answer (with real project reflection) Situation: In production, our payment service response time spiked from 20ms to 8 seconds during peak traffic. No exceptions in logs. No OOM errors. No infrastructure alerts. But transactions were timing out and customers were getting charged without order confirmation. Task: As the backend engineer on call, my task was to identify the root cause across the entire request chain without taking the service down and restore normal response times within minutes. Action: First I checked what changed. Recent deployments. Config changes. Traffic patterns. Nothing obvious. Then I followed the request. Step 1: Check thread pool ExecutorService thread pool was at 100% utilization. All threads waiting. No threads available to process new requests. This was the symptom not the cause. Step 2: Find what threads were waiting on Thread dump showed all threads blocked on database connection pool. HikariCP pool size was 10. All 10 connections held open. None being released. Step 3: Find why connections weren't releasing One specific query introduced in last deployment. Missing index on a foreign key column. Full table scan on every transaction. 100ms query became 7 second query under load. Connection held for 7 seconds per transaction. Pool exhausted in seconds. Step 4: Immediate fix Increased connection pool size temporarily bought 10 minutes. Added database index query dropped from 7 seconds to 8ms. Thread pool cleared instantly. Response time back to 20ms. Step 5: Permanent fix Added query performance testing to CI/CD pipeline. EXPLAIN ANALYZE on every new query before deployment. Connection pool monitoring alert at 70% utilization. Never caught this way again. Result: Service restored in 11 minutes. Root cause identified and fixed permanently. Incident led to mandatory query review process for all future deployments. Zero recurrence in 14 months. This is what separates a developer who builds features from an engineer who owns systems. Anyone can write code that works at 100 users. Production engineers write code that survives at 100,000. The concepts behind this answer thread pools, connection pooling, query optimization, HikariCP internals are exactly what I documented in my Java Backend Engineering Guide. Not theory. Real production scenarios. Java Backend Engineering Guide → https://lnkd.in/dTvYVutD Use SDE20 to get 20% off. Stay Hungry, Stay FoolisH!
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