Does making a Reentrant Lock static and make it a

2020-06-03 02:47发布

问题:

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

回答1:

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).



回答2:

Creating a static Lock is equivallent to

synchronized(MyClass.class){

}

Its in essence a class level lock