Question

According to JLS Section §8.4.3.6:

A synchronized method acquires a monitor (§17.1) before it executes.

For a class (static) method, the monitor associated with the Class object for the method's class is used.

In this synchronized method move class level lock is acquired. So which Class object is exactly used for obtaining this lock. Is it Interface.class or ClassImplementingInterface.class? If it is the later is there any scenario where we can have interface monitors? or rather does interface have a monitor?

I have read each object is associated with a monitor and in case of static locks monitor is obtained on corresponding Class object. As we can do Interface.Class which means interface has corresponding Class object can we get a lock on that monitor without explicitly saying synchronized(Interface.class).

Was it helpful?

Solution

An interface is a type and can therefore get its Class<?> object

public interface MyTest {}
...
Class<?> clazz = MyTest.class;

However, for Java 7 and before, your question is moot since interfaces cannot have static methods and static methods cannot be overriden, so it will always get the Class object of the class it's being called on.

public class StaticTest {
    public static synchronized void test() {
        // something
    }
}

Calling StaticTest.test() will synchronize on the StaticText.class object.

As for instance methods with a synchronized modifer, it would again be the calling object's monitor (lock) that you would acquire.

In Java 8, you can declare and define static methods in interfaces, but they cannot be modified with the synchronized keyword.

InterfaceMethodModifier:
    (one of)
    Annotation public
    abstract default static strictfp

It's again a non-issue.


To answer

is there any scenario where we can have interface monitors

not with a synchronized modifier. But you can always use a synchronized block on an interface's Class object.

synchronized (MyTest.class) {...}

but really, why would you do that? I think it would be confusing for people reading your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top