Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

java - Is this variable being safely accessed by using synchronization?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...