Junior — Middle
In what situations is it necessary to use synchronized code blocks?
sobes.tech AI
Answer from AI
Synchronized code blocks in Java are used to ensure thread safety when accessing shared resources from multiple threads.
The need arises when:
- Multiple threads may modify shared data simultaneously (e.g., collections, variables).
- To avoid race conditions.
- To guarantee the atomicity of operations.
Example: if multiple threads add elements to a shared list, without synchronization, data loss or structure corruption may occur.
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
Here, the synchronized keyword ensures that only one thread executes the method at a time, preventing incorrect modifications.