Junior — Middle
What is the main purpose of executing critical sections using the synchronized block in Java?
sobes.tech AI
Answer from AI
The synchronized block in Java is used to ensure mutual exclusion when accessing critical sections of code. Its main purpose is to prevent multiple threads from executing this code simultaneously, thereby avoiding race conditions and ensuring data correctness.
When a thread enters a synchronized block, it acquires the monitor (lock) of the object, and other threads attempting to enter the same block with the same monitor will wait until the first thread exits the block.
Example:
public void increment() {
synchronized(this) {
counter++;
}
}