Does making a Reentrant Lock static and make it a

2020-06-03 02:53发布

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

2条回答
地球回转人心会变
2楼-- · 2020-06-03 03:41

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

查看更多
等我变得足够好
3楼-- · 2020-06-03 03:44

Creating a static Lock is equivallent to

synchronized(MyClass.class){

}

Its in essence a class level lock

查看更多
登录 后发表回答