user5451270
user5451270

Reputation: 79

Class level locking in java

Suppose I have a class on which I want to obtain class level lock. Do I necessarily need to have static methods inside the class to achieve the class level locking or by simply using synchronized(MyClass.class) will do the job without any static methods in it.

Upvotes: 0

Views: 263

Answers (2)

Chinmay
Chinmay

Reputation: 113

You can use ReentrantLock as well:

private static final Lock lock1 = new ReentrantLock();  
public static void main(String... strings) {
    lock1.lock();
    //do Something
    lock1.unlock();
}

Upvotes: 0

Stephen C
Stephen C

Reputation: 718758

Synchronizing on the Class object will do the trick.

Alternatively, if you want your class-level lock to not interfere with a different class-level lock on the same class, then declare a private static field to be the lock; e.g.

public class MyClass {
    private static final Object myLock = new Object();
    private static final Object anotherLock = new Object();
    ...
}

Now we have two distinct "class-level" locks for the same class.

Upvotes: 3

Related Questions