“Synchronized (this)” vs. “synchronized ((baseClass) this)” in Java

Is this variable being safely accessed by using synchronization? Heirs of

For the following procedures,

Class SubClassB extends SuperClassA {
     protected int c;

     public void inc() {
          synchronized (this) {
               c++;
          }
     }

     public void dec() {
          synchronized ( (SuperClassA) this) {
               c--;
          }
     }
}

Is the counter "C" thread safe to access? I'm not sure whether superclassa is a valid object that references the synchronization block for "this" in the "dec()" method? If so, do the two synchronization blocks lock the same "this" object? (in my opinion, "superclassa" is not equal to "this")

This strange simulation code comes from the following real-life examples, in which superclassa is a base class that is not modified,

Class SuperClassA {
     protected int c;

     public void dec() {
          synchronized (this) {
               c--;
          }
     }
}

Class SubClassB extends SuperClassA {

     public void inc() {
          synchronized (this) {
               c++;
          }
     }

     public void dec() {
          super.dec();
     }
}

In this example, the "dec()" method in subclassb calls the "dec()" method of its superclass, which locks the "this" object I think is "superclassa. This" If the locking object in the "inc()" method of subclassb is not exactly the same as that in the "dec()" method of subclassb, I want to know that the inherited counter "C" in subclassb may not be safely accessed by different threads I think there is some ambiguity in using the "this" reference in the synchronization block

In the real-life example, if I want the counter "C" of subclassb to be thread safe, I need to add more synchronization blocks to its "dec()" method, like this,

Class SubClassB extends SuperClassA {

     public void inc() {
          synchronized (this) {
               c++;
          }
     }

     public void dec() {
          synchronized (this) {
               super.dec();
          }
     }
}

But it seems that the blocks added in this way are not elegant and may be redundant!

Some people have some ideas about these problems Thank you in advance

Lawrence

Solution

Yes, it uses the same lock object

Yes

Yes Even if an instance is converted to an instance that can be converted to (or even object), it will still reference the same object

This is superfluous Additional synchronization is required only if you call multiple synchronization methods and the combined effect must be atomic

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>