Question

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?

Was it helpful?

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.

OTHER TIPS

I had given a try on it in my blog. I hope it helps

The idea here is to create class C and D as follows

class C {

    static A a = new A(); //I have created new instances of A and B
    static B b = new B(); //The same instances can be passed to C and D via constructor

    static synchronized void da1() {
        a.a1();
    }

    static synchronized void db1() {
        b.b1();
    }
}

class D {

    static A a = new A();
    static B b = new B();

    static synchronized void ca2() {
        a.a2();
    }

    static synchronized void cb2() {
        b.b2();
    }
}

If you consider the case where A's a1() and B's b1() should be mutually exclusive, then you should redirect both of them through C.

In C, both the methods are static synchronized, that means only one method can be executed at any instance of time (lock is the class object itself). Hence when a1() is executed, thread executing b1() will wait and vise versa.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top