Skip to main content

Posts

Showing posts with the label Java Multithreading Thread Safety Race Condition Synchronized in Java Java Interview Questions Banking Example Java Concurrency in Java Java Tips and Tricks

💣 Without Thread Safety — Chaos in Banking

🎯 1. Setting the Scene — The Interview Moment Imagine this… Interviewer: “So, how would you handle multiple threads accessing a shared bank account in Java?” Me: “You mean… like multiple ATMs punching the same account balance at the same time?” 🏦💳 Interviewer: smiles like a villain in a heist movie 😈 “Exactly.” 🚨 2. Without Thread Safety — What Happens? Bad Code (Singleton Bean or Shared Object) class BankAccount { private int balance = 1000; // Shared among threads public void deposit(int amount) { balance += amount; // 🚨 Not synchronized System.out.println(Thread.currentThread().getName() + " deposited ₹" + amount + ", Balance: ₹" + balance); } public void withdraw(int amount) { if (balance >= amount) { balance -= amount; // 🚨 Not synchronized System.out.println(Thread.currentThread().getName() + " withdrew ₹" + amount + ", Balance: ...