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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With