views:

41

answers:

1

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.

+6  A: 

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.

Eugene Kuleshov
I'm not sure it's just theory. Every time you access the field you need to have the final field barrier for correctness. It is "theoretical" if the JIT optimises the second read away as it is a final field.
Jed Wesley-Smith