Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a case in which a Java class has a superclass that contains a synchronized block.

Class SuperClassA {
     private Bitmap bmpA;

     protected abstract Bitmap createBitmap();

     public void run() {
          synchronized (this) {
               bmpA = createBitmap();
          }
     }

     // some other codes.
}

Class SubClassB extends SuperClassA {
     private Bitmap outBmpB;

     protected Bitmap createBitmap() {
          outBmpB = ..... // create and process "outBmpB".

          Bitmap bmp;
          bmp = ..... // create and process "bmp".
          return bmp;
     }

     public Bitmap getOutBmpB() {
          Bitmap tempBmp;
          synchronized (this) {
               tempBmp = outBmpB.clone();
          }
          return tempBmp;
     }

     // some other codes.
}

The "getOutBmpB()" method in Class B is run by a thread while the inherited "run()" method in ClassB is run by another thread. The "createBitmap()" method implemented in ClassB should be run in a synchronized block inside the "run()" method.

My question is that I am not sure whether the newly defined class variable "outBmpB" in ClassB is safely accessed by the two threads. I am not sure the "synchronized (this)" block in the "run()" method would also "lock" the "outBmpB" variable defined just in ClassB ? If not, then could I add a "synchronized (this)" block in the "createBitmap()" implementation. e.g.

 protected Bitmap createBitmap() {
      synchronized (this) {
           outBmpB = ..... // create and process "outBmpB".
      }

      Bitmap bmp;
      bmp = ..... // create and process "bmp".
      return bmp;
 }

Thanks for any suggestion.

Lawrence

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
251 views
Welcome To Ask or Share your Answers For Others

1 Answer

You don't have to synchronize it since it is already synchronized in super class and there are no other calls, but you should. Your implementation of createBitmap() relies on implementation details from the super class. Do synchronization at every point you access your shared fields.

Due to this facts your current subclass' code is very error-prone!

While it is questionable to ever synchronize over this, it is a much better idea to synchronize over a private object nobody else can access. So your code cannot be broken by clients using your class objects and synchronize on it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...