0

I have two classes

public class A {
    private byte[] buf;
    public synchronized void foo() {
        // does something with buf
    }
    public class B {
        public synchronized void bar() {
            // also does something with buf
        }
    }
}

As far as I know, method bar() is synchronized on an instance of class B. How can I synchronize it on the object of class A in order to protect the buf?

Anthony
  • 12,407
  • 12
  • 64
  • 88

1 Answers1

1

As explained in this answer, you can do the following:

public class A {
    private byte[] buf;

    public synchronized void foo() {
        // does something with buf
    }

    public class B {
        public void bar() {
            synchronized (A.this) {
                // also does something with buf
            }
        }
    }
}

This works only, since you use a nested class that has a reference to its parent class. However, if you only want to synchronize the usage of the variable buf you can also do this:

public class A {
    private byte[] buf;

    public void foo() {
        synchronized (buf) {
            // does something with buf
        }
    }

    public class B {
        public void bar() {
            synchronized (buf) {
                // also does something with buf
            }
        }
    }
}
Community
  • 1
  • 1
Stefan Dollase
  • 4,530
  • 3
  • 27
  • 51