I was reading about java threads and happened to read this blog. In the blog I came across a statement:
During the execution of a synchronized method, the thread holds the monitor for that method's object, or if the method is static, it holds the monitor for that method's class.
Can anyone please tell me what is the difference between:
It means that a synchronized instance method is broadly equivalent to:
public class FooClass {
public void foo() {
synchronized(this) {
...
}
}
}
Whereas a synchronized static method is broadly equivalent to:
public class FooClass {
public static void foo() {
synchronized(FooClass.class) {
...
}
}
}
So in the instance method case it will synchronize on an instance of FooClass
(and calls to foo
in other threads on other instances will not block), whereas in the static method case it synchronizes on the Class
object itself.
Note that for the static method version, it's the class containing the method which is important - even if the method is notionally called "on" a subclass (e.g. SubFooClass.foo()
) the method still obtains a monitor on the class in which it's declared.
See JLS section 8.4.3.6 for more details.
See more on this question at Stackoverflow