Idiomatic use of ReentrantLock in Concurrency package [duplicate]

对着背影说爱祢 提交于 2019-12-05 04:34:59

问题


While browsing through the source code of the java.util.concurrency package, I noticed an idiomatic use of ReentrantLock that I had not seen before: member RentrantLock variables were never accessed directly from within a method - they were always referenced by a local variable reference.

Style #1 e.g from java.util.concurrent.ThreadPoolExecutor

private final ReentrantLock mainLock = new ReentrantLock();
...
// why a local reference to final mainlock instead of directly using it?
final ReentrantLock mainLock = this.mainLock; 
mainLock.lock();
try {
...     
} finally {
  mainLock.unlock();
}

However, in other places the final member variable is used directly, without first obtaining a local reference.

Style #2 e.g. from Java Concurrency in Practice

private final Lock lock = new ReentrantLock();
...
// here the final lock is used directly
lock.lock();   
try {
...
} finally {
lock.unlock();
}

I would like to understand what are the benefits of using Style #1 over Style #2?

Thanks

Update

Thanks for all of responses, especially Ben Manes for first identifying performance. As a result I was able to discover the following additional details

  1. Doug Lea introduced this idiom in 2003 with a comment "cache finals across volatiles"
  2. According to Doug, it is "for performance-critical code like that inside j.u.c." and while "It's not a recommended practice", he "does not discourage it either"
  3. Brian Goetz (author of JCIP) also agrees that unless it is for performance-critical applications "don't worry"

回答1:


Ben Manes linked to a discussion in the comments that talks about JIT optimisation. Apparently the hotspot compiler will not optimise the loads of a final field because it can be modified via reflection or with the Unsafe class.

Therefore this mechanism gives a minor speed improvement allowing JIT to optimise loads of the lock instance. They didn't go into detail of which optimisation would occur, but I suspect the optimisation is for preventing reloading the instance from main memory. This would allow a Thread to use the Re-entrant lock multiple times without penalty.

Unfortunately this answer is speculation based upon a mailing list discussion. If someone can correct me please go ahead!



来源:https://stackoverflow.com/questions/8089920/idiomatic-use-of-reentrantlock-in-concurrency-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!