Java
synchronized
Learn critical sections with synchronized.
synchronized
The synchronized keyword turns a method or block into a critical section that only one thread can execute at a time. This makes access to shared data safe.
class Counter {
private int count = 0;
public synchronized void inc() {
count++;
}
}
When two threads call inc() at the same time, one waits for the other. This ensures count increments correctly. A synchronized block is also possible: synchronized(this) { ... }. Excessive use serializes threads; be careful.
synchronized block
To lock only part of a method rather than the whole method, use a synchronized block. This means a smaller critical section and less waiting.
public void add(int n) {
synchronized (this) {
count += n;
}
}
Here this is the lock object. Different objects give different locks; separate parts can then run in parallel. Choosing the right lock object matters for performance and correctness.
Exercise Apply synchronized with a Counter
Define a Counter class with a private int count = 0 field. A public synchronized void inc() method does count++. A public int get() method returns count. In a SyncDemo class write main; create a Counter instance, call inc() three times and print get().
Show example solution
class Counter {
private int count = 0;
public synchronized void inc() {
count++;
}
public int get() {
return count;
}
}
class SyncDemo {
public static void main(String[] args) {
Counter c = new Counter();
c.inc();
c.inc();
c.inc();
System.out.println(c.get());
}
}
Test yourself
-
What does a synchronized method provide?
- Faster method execution
- Method renaming
- Static method
- Only one thread at a time
Show answer
Only one thread at a time — synchronized allows only one thread at a time.
-
Match synchronization concepts
- synchronized
- Mutual exclusion
- lock object
- Represents the lock
- critical section
- Single-thread region
- race condition
- Race bug
-
Complete the synchronized method
class Counter {
private int count = 0;
public ____ void inc() {
count++;
}
}
Show answer
class Counter {
private int count = 0;
public synchronized void inc() {
count++;
}
}
Next lesson: wait and notify