Synchronization & Thread Safety
When multiple threads access shared data simultaneously, race conditions can corrupt data. Synchronization ensures only one thread can access critical sections at a time, maintaining data integrity. This is a foundational concept in enterprise application development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world Java experience. Take your time with each section and practice the examples
45 min•By Priygop Team•Last updated: Feb 2026
Synchronization Example
Example
class BankAccount {
private double balance;
private String owner;
BankAccount(String owner, double balance) {
this.owner = owner;
this.balance = balance;
}
// synchronized — only one thread at a time
synchronized void deposit(double amount) {
double current = balance;
try { Thread.sleep(10); } catch (InterruptedException e) {}
balance = current + amount;
System.out.println("Deposited $" + amount + " | Balance: $" + balance);
}
synchronized void withdraw(double amount) {
if (balance >= amount) {
double current = balance;
try { Thread.sleep(10); } catch (InterruptedException e) {}
balance = current - amount;
System.out.println("Withdrew $" + amount + " | Balance: $" + balance);
} else {
System.out.println("Insufficient funds for $" + amount);
}
}
double getBalance() { return balance; }
}
public class SyncDemo {
public static void main(String[] args) throws InterruptedException {
BankAccount account = new BankAccount("Alice", 1000);
// Multiple threads accessing the same account
Thread depositor = new Thread(() -> {
for (int i = 0; i < 5; i++) {
account.deposit(100);
}
});
Thread withdrawer = new Thread(() -> {
for (int i = 0; i < 5; i++) {
account.withdraw(50);
}
});
depositor.start();
withdrawer.start();
depositor.join();
withdrawer.join();
System.out.println("\nFinal balance: $" + account.getBalance());
System.out.println("Expected: $1250 (1000 + 500 - 250)");
}
}Try It Yourself: Thread-Safe Counter
Try It Yourself: Thread-Safe CounterJava
Java Editor
✓ ValidTab = 2 spaces
Java|37 lines|1424 chars|✓ Valid syntax
UTF-8