Sobes.tech
Junior — Middle

Kuidas töötab synchronized-mehhanism, kui seda kasutatakse staatilise funktsiooniga monitoori kontekstis?

sobes.tech AI

Vastus AI-lt

When a method is declared as synchronized static in Java, the monitor (lock) is acquired at the class level, not at the instance object level. This means that when such a method is called, the thread locks the class monitor (Class object), and no other threads can execute other static synchronized methods of the same class simultaneously.

Example:

public class Example {
    public static synchronized void staticSyncMethod() {
        // locks the monitor of the class Example.class
        // critical section
    }
}

Therefore, synchronized on a static method ensures mutual exclusion at the class level, not on a specific object. This is useful when you need to synchronize access to static resources or variables of the class.