Sobes.tech
Junior — Middle

Kas Java-s saab kasutada synchronized-muutujat staatilisele meetodile?

sobes.tech AI

Vastus AI-lt

Yes, in Java, you can use the synchronized modifier for static methods. In this case, the locking occurs at the class level (the Class object), not at the instance level.

This means that if one thread executes a static synchronized method, other threads attempting to call any other static synchronized method of the same class will be blocked until the lock is released.

Example:

public class Example {
    public static synchronized void staticMethod() {
        // code synchronized on the Example.class object
    }
}

Thus, synchronized for static methods ensures thread safety at the class level.