Why is lock captured to a local variable
-
01-06-2021 - |
Question
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();
La solution
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.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow