Junior — Middle
What does the use of the synchronized keyword mean when synchronizing an object in Java?
sobes.tech AI
Answer from AI
The synchronized keyword in Java is used to ensure mutual exclusion when accessing an object or a block of code by multiple threads. It guarantees that only one thread can execute the synchronized code for a given object at a time.
When a method or block is marked as synchronized, the thread entering it acquires the monitor (lock) of the object. Other threads attempting to enter the same synchronized block or method for that object will wait until the monitor is released.
Example:
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
In this example, the increment method is synchronized to prevent multiple threads from changing the count variable simultaneously, which avoids race conditions.