Sobes.tech
Junior — Middle

How to implement synchronization in a static method using synchronized?

sobes.tech AI

Answer from AI

To synchronize a static method using the synchronized keyword, a class-level lock is used instead of an instance lock. This means that the monitor is the Class object of the respective class.

Example of synchronizing a static method:

public class MyClass {
    public static synchronized void staticMethod() {
        // code that will be executed by only one thread at a time
    }
}

Similarly, you can use a synchronized block inside a method:

public class MyClass {
    public static void staticMethod() {
        synchronized (MyClass.class) {
            // synchronized code
        }
    }
}

Thus, when calling a static synchronized method or synchronizing on the class, it guarantees that only one thread can execute this code for the given class at a time.

How to implement synchronization in a static method… - sobes.tech