Search code examples
javamultithreadingsynchronizationthread-safetyjava-threads

Can we have multiple static locks in a class in java


I have multiple methods on which I would like to have static lock so that no two objects can access one method but at the same time different methods do not get locked with those object and can run independently.

class A {
    private static final A lock1 = new A();
    private static final B lock2 = new B();

    public void method1() {
        synchronized (lock1) {
            // do something
        }
    }

    public void method2() {
        synchronized (lock2) {
            // do something
        }
    }
}

Now I want these two methods to be independent of each other when it gets locked but at the same time I want multiple instances of same class to be locked at single method.

How can this be achieved ? By using different class ? Can this be achieved by doing just this ?


Solution

  • First, this is sufficient:

    private static final Object lock1 = new Object();
    private static final Object lock2 = new Object();
    

    Then, with your implementation, method1 and method2 are independent of each other, but only one instance of method1 or method2 can run among all instances of A. If you want to allow different concurrent instances of A so that method1 and method2 of different instances can run concurrently, just declare the locks without static.

    In other words: if a1 and a2 are instances of A:

    • with static locks, if a1.method1 is running, a2.method1 cannot be run by another thread
    • without static, a1.method1 can be run by only one thread. a1.method1 and a2.method1 can run concurrently.