问题
In java JRE I saw the code
private final ReentrantLock lock;
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
Why is lock captured to a private variable? I would expect simply
public E poll() {
lock.lock();
回答1:
Primarily it is to ensure maximum performance. Although this is a real micro-optimisation, it's probably in performance-sensitive code, and you might as well make it.
You also need to be very careful that the lock reference you are using doesn't mutate. Sure make the field final
, but taking a final
local reference is locally explicit.
来源:https://stackoverflow.com/questions/10180656/why-is-lock-captured-to-a-local-variable