Java: A synchronized method in the superclass acquires the same lock as one in the subclass, right?

后端 未结 7 825
闹比i
闹比i 2021-02-12 10:12
class A {
    public synchronized void myOneMethod() {
        // ...
    }
}

class B extends A {
    public synchronized void myOtherMethod() {
        // ...
    }
}
         


        
相关标签:
7条回答
  • 2021-02-12 10:47

    From the conceptual viewpoint, the mutex integrity of some inheritance scenarios would be broken if synchonized methods of class A would only protect A's data in the context of subclass B. After all, not all of A's data is required to be private.

    Imagine that you want to slightly extend the functionality of one method of A while keeping the rest of A's functionality including mutex protection. If A were only protecting itself, you would end up having to override all of A's synchronized methods to lift the original synchronization mechanism to the new subclass. Not very attractive and also not very efficient.

    0 讨论(0)
提交回复
热议问题