Acquiring inner-class lock using outer-class locks?

匿名 (未验证) 提交于 2019-12-03 02:41:02

问题:

I have an outer class A and that has a public inner class, the structure is as follows -:

public class A{        public int x;        public class B{         private static final int y;       }        public synchronized int method1(){              return x+ B.y;       } } 

the question is if I used synchronized keyword on every method of the class A will it also lock the members of the inner class as well?

回答1:

if I used synchronized keyword on every method of the class A will it also lock the members of the inner class as well?

No it won't.

You seem to be confused in a number of respects here.

  • Using a primitive mutex (e.g. via a synchronized method) only locks against other threads that are synchronizing on the same mutex.

  • When you call a synchronized instance method, the mutex you are acquiring is the mutex for this ... the target object.

  • In your example, it seems that you want to lock a static field, not an instance field.


If I understand correctly what you are trying to do, the correct way to do it is something like this:

 public synchronized int method1(){      synchronized (B.class) {          return x + B.y;      }  } 

Note that this involves acquiring two mutexes, so you need to make sure that your code always acquires them in the same order. (If you don't, then there is a risk of deadlocks.)

You would get the same effect if you created and called a synchronized static method on B for getting the value of the y field.



回答2:

No, the inner class and outer class are two different class objects, they will not be the same. I suggest creating a field in the outer class to manually synchronize on.



回答3:

An example with a single mutex on 2 objects. Both Objects can change a variable x.

 public class A {        private Object mutex = new Object();       private int x;       private B b = new B();        public class B {         private int y;          public int method() {                    synchronized(mutex) {               return x++;           }          }       }        public int method() {            synchronized(mutex) {              return x += b.y;          }       } }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!