Race Condition : happens when multiple threads access and modify shared data at the same time, and the final result depends on the timing of execution. example: int count = 0; public void increment() { count++; } two threads execute count++ simultaneously: Both read count = 0 Both increment to 1 Both write back 1 Final result = 1 instead of 2 Problem: Data inconsistency Unpredictable results Solution: Use synchronization (synchronized) Use locks (ReentrantLock) Use atomic classes (AtomicInteger) Thread Starvation : thread is “waiting forever” while others keep running. example: Thread t1 = new Thread(task); t1.setPriority(Thread.MAX_PRIORITY); Thread t2 = new Thread(task); t2.setPriority(Thread.MIN_PRIORITY); t2 may rarely or never execute. problem: Some threads never complete Solution: ReentrantLock lock = new ReentrantLock(true); #Java #BackendDevelopment #SoftwareEngineering #MultiThreading #Concurrency #JavaPerformance #CodingTips #Programming #SystemDesign
Preventing Data Inconsistency with Synchronization
More Relevant Posts
-
Last week, we faced a critical production issue that reminded me how tricky multithreading can be in Java. 🔍 Problem: Our application suddenly became slow under load. CPU usage was low, but requests were timing out. 🧠 Root Cause: After analyzing thread dumps using tools like jstack and VisualVM, we discovered a classic deadlock situation. Two threads were waiting on each other’s locks — and nothing was moving forward. ⚠️ Key Learnings: Always maintain a consistent lock ordering to avoid deadlocks Avoid excessive use of synchronized blocks Prefer high-level concurrency utilities like ExecutorService, ReentrantLock, and ConcurrentHashMap Monitor thread pools in production (size, queue, rejection policy) Use tools like jconsole, VisualVM, and thread dumps regularly 💡 Pro Tip: Multithreading issues rarely appear in development — they show up under real traffic. Always design with concurrency in mind. 👨💻 As developers, writing correct concurrent code is not just a skill — it's a responsibility. #Java #Multithreading #BackendDevelopment #ProductionIssues #SoftwareEngineering #Debugging #TechLearning
To view or add a comment, sign in
-
🚀Day 39 #LeetCode 199 – Binary Tree Right Side View Ever wondered what a binary tree looks like from the right side? 👀 Let’s break it down! 🧠 Problem Insight When you observe a binary tree from the right, at every level you only see one node — the rightmost node. 👉 So the goal is simple: Capture the last node at each level ⚡ Approach (Level Order Traversal - BFS) ✔ Traverse the tree level by level ✔ At each level, pick the last node ✔ Add it to the result 📊 Complexity ⏱ Time: O(n) 📦 Space: O(n) 🔥 Key Takeaway 👉 Rightmost node at each level = Visible node 💡 Example Input: [1,2,3,null,5,null,4] Output: [1,3,4] 💬 Have you tried solving this using DFS (Right-first traversal)? Drop your approach below! #LeetCode #DataStructures #BinaryTree #CodingInterview #Java #Programming
To view or add a comment, sign in
-
-
𝐓𝐡𝐫𝐞𝐚𝐝 𝐒𝐚𝐟𝐞𝐭𝐲 - 𝐭𝐡𝐞 𝐛𝐮𝐠 𝐭𝐡𝐚𝐭 𝐥𝐢𝐞𝐬 𝐪𝐮𝐢𝐞𝐭𝐥𝐲 𝐮𝐧𝐭𝐢𝐥 𝐩𝐞𝐚𝐤 𝐭𝐫𝐚𝐟𝐟𝐢𝐜. Multiple threads sharing the same memory is powerful. It is also dangerous. 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐢𝐭? When two threads read and write the same variable at the same time the result becomes unpredictable. This is called a Race Condition. No crash. No exception. Just silently wrong results. A payment processed twice. A counter off by thousands. A balance that never adds up. 𝐖𝐡𝐞𝐧 𝐝𝐨𝐞𝐬 𝐢𝐭 𝐡𝐚𝐩𝐩𝐞𝐧? → Shared counters updated by multiple threads → Shared collections read and written simultaneously → Singleton beans with mutable state in Spring → Cached values updated without synchronization 𝐇𝐨𝐰 𝐭𝐨 𝐩𝐫𝐞𝐯𝐞𝐧𝐭 𝐢𝐭? → Use Atomic types for simple counters and flags → Use immutable objects wherever possible → Use thread-safe collections like ConcurrentHashMap → Avoid shared mutable state entirely when you can → Scope variables locally - local variables are always safe 𝐓𝐡𝐞 𝐦𝐢𝐧𝐝𝐬𝐞𝐭 𝐬𝐡𝐢𝐟𝐭: Stop asking "does this work?" Start asking "what happens when 1000 threads hit this simultaneously?" Thread safety bugs don't show in unit tests. They show in production at the worst possible moment. #Java #ThreadSafety #Concurrency #RaceCondition #BackendEngineering
To view or add a comment, sign in
-
Day 50/75 — Climbing Stairs Today’s problem was a classic dynamic programming question — counting the number of distinct ways to reach the top. Approach: • Recognize it as a Fibonacci pattern • Each step = sum of previous two steps • Optimize space using two variables instead of an array Key logic: int current = prev1 + prev2; prev2 = prev1; prev1 = current; Time Complexity: O(n) Space Complexity: O(1) A fundamental problem that builds strong intuition for DP and recurrence relations. Halfway there — consistency paying off 🔥 50/75 🚀 #Day50 #DSA #DynamicProgramming #Java #Algorithms #LeetCode
To view or add a comment, sign in
-
-
Day 55/100 – LeetCode Challenge Problem: Triangle Today I solved the “Triangle” problem, which is a classic dynamic programming question focused on finding the minimum path sum from top to bottom. Instead of starting from the top and exploring all possible paths, I approached this problem from the bottom. I initialized a DP array with the values of the last row of the triangle. Then, I moved upward row by row, updating each element by adding the minimum of the two adjacent values from the row below. This bottom-up approach reduces the problem size at each step and avoids unnecessary recomputation. By the time I reached the top, the first element of the DP array represented the minimum path sum. This method is efficient because it reuses space and avoids building a full 2D DP table. The solution runs in O(n²) time with O(n) space complexity. This problem reinforced how changing the direction of thinking — bottom-up instead of top-down — can simplify dynamic programming problems significantly. Fifty-five days in. The focus is now on writing optimal solutions with better space efficiency. #100DaysOfLeetCode #Java #DSA #DynamicProgramming #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
#Post9 In last post(https://lnkd.in/ddzdPfvQ), we learned about selecting optimal number of threads for our process. Common assumption is, a thread is either running or not. In reality, a thread spends most of its life NOT running. To understand multithreading properly, we need to understand the lifecycle of a thread. Let’s break it down. 1. New A thread is created but not started yet. Thread t = new Thread(); At this point, it’s just an object in memory. 2. Runnable Once you call start(), the thread becomes ready to run. It doesn’t mean it is running immediately. It simply means it is waiting for CPU scheduling. 3. Running When the CPU scheduler picks the thread, it starts executing. This is the state where actual work happens. 4. Blocked A thread enters this state when it is trying to acquire a lock, but another thread already holds it. Until the lock is released, the thread cannot proceed. 5. Waiting A thread goes into this state when wait() is called. • It pauses execution indefinitely • Releases the monitor lock • Becomes runnable again only after notify() or notifyAll() 6. Timed Waiting A thread waits for a specific amount of time. Examples: • sleep() • join() • wait(timeout) Important detail: • sleep() does NOT release the lock • wait(timeout) releases the lock 7. Terminated The thread has finished execution. Once terminated, it cannot be started again. Below is a reference diagram of the thread lifecycle. We will revisit this as we go deeper into concepts like start(), wait(), and synchronization Key takeaway A thread is not constantly running. In real systems, most threads are: • Waiting • Blocked • Or ready to run Understanding this helps build the foundation for: • Debugging concurrency issues • Avoiding deadlocks • Writing efficient multithreaded code In the next post, we will look at different ways to create threads in Java. #Java #Multithreading #Concurrency #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
#day24 🛠️ Debugging multithreading — what happens in production Concurrency bugs don’t always show in development — they appear in production ⚠️ 👉 Key tools I explored: Thread dump (jstack) VisualVM / JConsole Java Flight Recorder 👉 Common issues: Deadlocks High CPU usage Thread contention 💡 Example insight: Too many BLOCKED threads → lock contention → performance bottleneck 👉 Fix: reduce synchronization or use concurrent structures #Java #Multithreading #Debugging #PerformanceTuning #Concurrency #JavaDeveloper #InterviewPreparation #LearningInPublic
To view or add a comment, sign in
-
“Most people try to overcomplicate this one… but the simplest approach wins.” Day 69 — LeetCode Progress Problem: Height Checker Required: Given an array of student heights, return the number of indices where the heights are not in the expected non-decreasing order. Idea: If we sort the array, we get the expected order. Now just compare the original array with the sorted version — mismatches are the answer. Approach: Create a copy of the original array Sort the copied array Traverse both arrays: Compare elements at each index If they differ → increment count Return the count Time Complexity: O(n log n) Space Complexity: O(n) #LeetCode #DSA #Java #Arrays #Sorting #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🔥 Day 36 of #LeetCode Journey ✅ Problem: Minimum Distance Between Three Equal Elements I Today’s problem was about finding the minimum distance between three equal elements in an array. 💡 Key Idea: Instead of checking all combinations, we track indices efficiently: Store the last two occurrences of each number When a third occurrence appears, calculate the distance Keep updating the minimum distance 🧠 What I Learned: Optimizing from brute force to O(n) approach Using HashMap effectively for tracking indices Thinking in terms of patterns instead of combinations ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(n) 🔍 Example: Input: [1,2,1,1,3,1] Output: 3 Small optimizations make a big difference 💡 Staying consistent and improving every day! #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #Programming #ProblemSolving
To view or add a comment, sign in
-
-
More threads ≠ faster system. It often makes it slower. Most devs don’t realize this until production. 🔹 What actually happens ❌ Context switching increases ❌ Threads spend time waiting ❌ Memory overhead grows 👉 Result: performance drops 🔹 Quick Reality Check 👉 CPU-bound → threads ≈ cores 👉 IO-bound → slightly more threads Anything beyond that = diminishing returns 🔹 What about Virtual Threads? Java’s Virtual Threads (Project Loom): ✔ Lightweight ✔ Handle massive concurrency ✔ Reduce thread management overhead BUT 👇 👉 They don’t remove CPU limits 👉 Bad design will still hurt performance 🔹 Real Insight Multithreading is not about more threads It’s about right threads 🔹 Quick Interview Questions 1️⃣ What is context switching? 2️⃣ CPU-bound vs IO-bound? 3️⃣ How to decide optimal thread count ? 4️⃣ What are Virtual Threads? 5️⃣ Can more threads reduce performance? 🔹 Final Thought 👉 Platform threads need control 👉 Virtual threads need understanding 💬 Be honest: Are you overusing threads in your system? #Java #Multithreading #Performance #VirtualThreads #Backend
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