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

Swifty McSwifterton
  • 2,637
  • 1
  • 30
  • 37

2 Answers2

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

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • 1
    Also see http://www.ibm.com/developerworks/java/library/j-jtp10264/ for more information about locks versus the synchronized keyword. – Michael Shopsin Jul 26 '11 at 15:26
  • 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? – Bobzone Dec 01 '17 at 01:10
  • @Bobzone I suggest to ask a new question. If I'd answer that here, only very few people would be able to find it. – Aaron Digulla Dec 08 '17 at 14:13
  • @AaronDigulla created this thread, as suggested : https://stackoverflow.com/questions/47722200/making-static-reentrantlocks – Bobzone Dec 08 '17 at 21:12
4

Creating a static Lock is equivallent to

synchronized(MyClass.class){

}

Its in essence a class level lock

John Vint
  • 39,695
  • 7
  • 78
  • 108
  • 1
    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. – Bill Poitras Nov 09 '11 at 15:07
  • 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. – John Vint Nov 09 '11 at 15:41