Category: java
What synchronized Does
Published on 27 Oct 2026
Explanation
The synchronized keyword ensures that only one thread at a time can execute code protected by the same monitor lock. It also establishes memory-visibility guarantees when threads release and later acquire that same monitor.
Code:
class Counter {
private int count;
public synchronized void increment() { count++; }
public synchronized int getCount() { return count; }
}
public class SynchronizedDemo {
public static void main(String[] args) {
Counter c = new Counter();
c.increment();
System.out.println(c.getCount());
}
}
Explanation
A synchronized instance method locks this. A synchronized static method locks the Class object. A synchronized block lets you protect only the critical section and can use a private lock object.
Code:
class Inventory {
private final Object lock = new Object();
private int stock = 5;
public void sell() {
synchronized (lock) {
if (stock > 0) stock--;
}
}
}
Explanation
Incrementing an integer is a read-modify-write operation, not an atomic operation. Synchronizing the increment method prevents threads using the same Counter instance from losing updates.
Code:
class SafeCounter {
private int count;
public synchronized void increment() { count++; }
public synchronized int value() { return count; }
}
public class CounterTest {
public static void main(String[] args) throws InterruptedException {
SafeCounter c = new SafeCounter();
Runnable task = () -> { for (int i = 0; i < 1000; i++) c.increment(); };
Thread a = new Thread(task), b = new Thread(task);
a.start(); b.start(); a.join(); b.join();
System.out.println(c.value()); // 2000
}
}
Explanation
Every Java object can act as a monitor. A thread entering synchronized code must acquire that monitor; another thread attempting to enter code protected by the same monitor waits until it is released.
Code:
public class MonitorDemo {
private final Object lock = new Object();
public void work() {
synchronized (lock) {
System.out.println("Inside critical section");
}
}
public static void main(String[] args) { new MonitorDemo().work(); }
}
Explanation
Synchronization only coordinates code that uses the same lock. Locking on different objects does not protect the same state. Prefer private, stable lock objects and avoid synchronizing on public objects or string literals.
Code:
class Resource {
private final Object lock = new Object();
private int value;
public void update() {
synchronized (lock) { value++; }
}
}