Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does making a Reentrant Lock static and make it a mutex?

In Brian Goetz's book, Java Concurrency in Practice, his example of a Reentrant lock is programmed like this:

Lock lock = new ReentrantLock();

However, I am curious to know if changing the above code to:

private static final Lock lock = new ReentrantLock();

causes the lock to now act as a mutex, or if it is unnecessary and redundant.

Thus, does the functionality of this code change if the lock is made private, static, and final?

lock.lock();
try {
    //method stuff
} finally {
    lock.unlock();
}

Thank you all in advance. Matt

like image 549
Swifty McSwifterton Avatar asked Apr 15 '11 15:04

Swifty McSwifterton


2 Answers

Yes.

final and private have no influence, of course, but static means that all instances share the same lock.

So if you have two instances, the code block can't be executed by two threads at the same time.

If the lock isn't static, each instance gets its own lock. That means that more threads can run the code at the same time (depending on which instance they work, of course).

like image 169
Aaron Digulla Avatar answered Oct 17 '22 21:10

Aaron Digulla


Creating a static Lock is equivallent to

synchronized(MyClass.class){

}

Its in essence a class level lock

like image 32
John Vint Avatar answered Oct 17 '22 21:10

John Vint