Search code examples
javamultithreadingjava.util.concurrent

Restricting method execution from other class method


Somebody asked me this question and I am not able to find out the solution, I have a class A with method a1 and a2:

Class A {a1() a2()}:

and a class B with method b1 and b2:

Class B {b1() b2()}

Considering multithreading environment i want to stop execution of b1 when a1 is called and same applies for b2 and a2. Both the objects are independent. Is this possible?


Solution

  • public class A {
        private final Object lock;
    
        public A(Object lock) {
            this.lock = lock;
        }
    
        public void a1() { 
            synchronized(lock) {
                ...
            }
        }
    }
    
    public class B {
        private final Object lock;
    
        public B(Object lock) {
            this.lock = lock;
        }
    
        public void b1() { 
            synchronized(lock) {
                ...
            }
        }
    }
    

    Now if you construct an A and a B and pass them the same lock object, The a1() and b1() methods of those two objects will be mutually exclusive:

    Object lock = new Object();
    A a = new A(lock);
    B b = new B(lock);
    

    If you want a2() and b2() to be mutually exclusive, then pass another lock object, and make these two methods synchronized on this other lock object.