Nearby lessons

74 of 125

Java - Synchronization

📌 What You Will Learn
  • What a thread is and how it is different from a process
  • Two ways to create a thread: Thread class and Runnable interface
  • The thread life cycle (states)
  • How threads cooperate: synchronized, wait and notify
  • The modern way: Executors, Callable and lambdas

Synchronization is a core concept of the Java language. This lesson explains The Problem — Race Condition and The Solution — synchronized with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

The Problem — Race Condition

When two threads change the same shared variable at the same time, the result can be wrong. This problem is called a race condition. Example: two threads add money to the same account, but the additions get lost.

Example01
JCode Cell
1class Account {
2 int balance = 1000;
3 void deposit(int amt) {
4 balance = balance + amt; // dangerous: two threads may read the same old value
5 }
6}

The Solution — synchronized

The synchronized keyword gives a lock. Only one thread at a time can enter a synchronized method or block. Others must wait outside until the lock is free.

In simple words: `synchronized` gives a lock so only one thread can enter the method at a time. The other threads wait outside until the lock is free, which fixes the race condition on shared data.
Example02
JCode Cell
1class Account {
2 int balance = 1000;
3 
4 synchronized void deposit(int amt) { // only one thread inside at a time
5 balance = balance + amt;
6 }
7}
8 
9class Test {
10 public static void main(String[] args) throws Exception {
11 Account a = new Account();
12 Thread t1 = new Thread(() -> a.deposit(500));
13 Thread t2 = new Thread(() -> a.deposit(500));
14 t1.start(); t2.start();
15 t1.join(); t2.join();
16 System.out.println("Final balance: " + a.balance); // always 2000
17 }
18}
Output
Final balance: 2000
📝 Key Takeaways
  • A thread is a small unit of work; a process is a running program.
  • Create a thread by extending Thread or (better) implementing Runnable.
  • Life cycle: NEW -> RUNNABLE -> BLOCKED/WAITING/TIMED_WAITING -> TERMINATED.
  • Shared data races when many threads change it; synchronized gives a lock.
  • wait/notify let threads talk; they need the lock.
  • Deadlock = threads waiting on each other's locks; avoid by consistent lock order.
  • Real projects use Executors + Callable instead of raw threads.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1