Does making a Reentrant Lock static and make it a mutex?
Asked Answered
S

2

13

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

Saltation answered 15/4, 2011 at 15:8 Comment(0)
E
23

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

Epperson answered 15/4, 2011 at 15:12 Comment(4)
Also see ibm.com/developerworks/java/library/j-jtp10264 for more information about locks versus the synchronized keyword.Getupandgo
Sorry to dig this post out of the ground, but I'm looking around this subject now. Im interested if creating a private static final ReentrantLock lock is not considered a code smell? I've read that static variables are evil, yet my current use case Im working on looks like ideal place to use one. Care to help?Gryphon
@Gryphon I suggest to ask a new question. If I'd answer that here, only very few people would be able to find it.Epperson
@AaronDigulla created this thread, as suggested : #47722700Gryphon
W
4

Creating a static Lock is equivallent to

synchronized(MyClass.class){

}

Its in essence a class level lock

Wallop answered 15/4, 2011 at 15:13 Comment(2)
Not exactly. The class is public, any caller can perform the lock. The Reentrant lock specified is private, so only the class can access that lock.Sequestrate
You're assuming the class is public and not a child, private, protected or package-protected. Nevertheless, my answer was more to demonstrate the relationship between the lock and the class.Wallop

© 2022 - 2024 — McMap. All rights reserved.