I have a methode foo in base class uses Synchronized (class name) , and two classes A and B that extends the base class. if i called foo from A instance and B instance in two different thread are they gonna be Synchronized. here’s a sample code :
class BaseClass {
void foo() {
synchronized(BaseClass.class)
// do something like increment count
}
}
class A extends BaseClass {
}
class B extends BaseClass {
}
A a = new A();
B b = new B();
//in thread 1
a.foo() ;
//in thread 2
b.foo() ;
Yes, that will be synchronized across all instances of all classes extending
BaseClass(includingBaseClassitself). TheBaseClass.classreference will basically be a single reference for the whole classloader. Do you really want that?Usually, when synchronization is required, static methods should synchronize on something static, and instance methods should synchronize on something related to the instance. Personally I don’t like synchronizing on either
thisor aClassreference – as both of those references are available elsewhere, so other code could synchronize on the same monitor, making it hard to reason about the synchronization. Instead, I would tend to have:(I typically actually just use
lockas the name; I’ve just made it more explicit here for clarity.)