0

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?

AnkitSablok
  • 3,021
  • 7
  • 35
  • 52

3 Answers3

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • actually I am working on the problem of coarse grain locking a linked list data structure where I have the following structure -: class LList{ public class Node{} public class InsertNode{}} and when a thread lets say T1 acquires a lock on the linked list data structure I want to ensure no other thread acquires a lock on either the individual nodes in the list and nor the list data structure how do I ensure that to happen. – AnkitSablok Sep 14 '13 at 04:53
  • @AnkitSablok - As above. Use two objects as mutexes. – Stephen C Sep 15 '13 at 00:20
0

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.

md_5
  • 630
  • 9
  • 26
0

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;
         }
      }
}
Ivan Voroshilin
  • 5,233
  • 3
  • 32
  • 61