synchronized
- Java course
- Advanced
- Lesson 58/82
- 5 min
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.
Practice 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().
Starter code
// Define the Counter class (private int count, synchronized inc, get)
// Write main in SyncDemo; call inc three times and print get's resultSample 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());
}
}Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a synchronized method provide?
- Faster method execution
- Method renaming
- Static method
- Only one thread at a time Correct answer
Explanation: synchronized allows only one thread at a time.
2 Match synchronization concepts
| Term | Meaning |
|---|---|
synchronized |
Mutual exclusion |
lock object |
Represents the lock |
critical section |
Single-thread region |
race condition |
Race bug |
3 Complete the synchronized method
class Counter {
private int count = 0;
public ____ void inc() {
count++;
}
}
class Counter {
private int count = 0;
public synchronized void inc() {
count++;
}
}
Explanation: synchronized makes the method a critical section.