I was recently checking implementation of the j.u.c.CopyOnWriteArrayList in OpenJDK’s sources and found that the lock variable defined inside the class, is redeclared with following statement
final ReentrantLock lock = this.lock;
inside all the methods which requires this variable. Any specific reason for doing such redeclaration of the variable (which is possibly hiding global variable). Cant we simply use object’s ‘lock’ field directly.
That is just a micro optimization technique. In theory, access to a local variable is faster then access to field and it may also result to a smaller bytecode. Though HotSpot compiler may actually optimize field access to a register call, so it won’t be different.