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 pro开发者_高级运维grammed 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
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).
Creating a static Lock is equivallent to
synchronized(MyClass.class){
}
Its in essence a class level lock
精彩评论