Sobes.tech
Junior — Middle

Is it possible to run two methods synchronized with synchronized in the same class simultaneously if these methods work with different objects?

sobes.tech AI

Answer from AI

In Java, the keyword synchronized can be used to synchronize at the instance level of an object or at the class level (static method). If two methods are synchronized on different objects, they can execute simultaneously because the locks are different.

For example, if methods are synchronized on this (the instance of the class), then two calls on different objects do not block each other. But if methods are synchronized on the same object (for example, a static object or the class itself), then they will execute sequentially.

Thus, if methods work with different objects and are synchronized on those objects, they can run concurrently.

Example:

class MyClass {
    private final Object lock1 = new Object();
    private final Object lock2 = new Object();

    public void method1() {
        synchronized(lock1) {
            // work with object 1
        }
    }

    public void method2() {
        synchronized(lock2) {
            // work with object 2
        }
    }
}

In this example, method1 and method2 can execute simultaneously because the locks are different.

Is it possible to run two methods synchronized with… - sobes.tech