Junior — Middle
In which cases should a static method with synchronization be used in Java?
sobes.tech AI
Answer from AI
A static method with synchronization in Java should be used when you need to ensure thread-safe access to shared resources related to the class, rather than a specific instance. For example, if a method modifies or reads static variables that may be accessed by multiple threads simultaneously, synchronization will prevent race conditions.
Synchronizing a static method locks the class monitor (Class object), not a specific instance, so all calls to this method from different threads will be executed sequentially.
Example:
public class Counter {
private static int count = 0;
public static synchronized void increment() {
count++;
}
public static synchronized int getCount() {
return count;
}
}
Here, synchronization is necessary to prevent multiple threads from modifying the count variable simultaneously.