在ArrayBlockingQueue,所有需要锁的方法final在调用之前将其复制到局部变量lock().
public boolean offer(E e) {
if (e == null) throw new NullPointerException();
final ReentrantLock lock = this.lock;
lock.lock();
try {
if (count == items.length)
return false;
else {
insert(e);
return true;
}
} finally {
lock.unlock();
}
}
Run Code Online (Sandbox Code Playgroud)
当字段是什么时,有没有理由复制this.lock到局部变量?lockthis.lockfinal
此外,它还在使用E[]之前使用本地副本:
private E extract() {
final E[] items = this.items;
E x = items[takeIndex];
items[takeIndex] = null;
takeIndex = inc(takeIndex);
--count;
notFull.signal();
return x;
}
Run Code Online (Sandbox Code Playgroud)
有没有理由将最终字段复制到本地最终变量?
看java的hashmap实现,无法理解一些行背后的原因.在下面从这里复制的代码中,在365-367行中,我无法理解他们为什么先将e.key赋值给k然后将==与key [(k = e.key)== key进行比较].为什么不直接做(e.key == key).此模式在代码中出现多次.
359
360 final Entry<K,V> getEntry(Object key) {
361 int hash = (key == null) ? 0 : hash(key.hashCode());
362 for (Entry<K,V> e = table[indexFor(hash, table.length)];
363 e != null;
364 e = e.next) {
365 Object k;
366 if (e.hash == hash &&
367 ((k = e.key) == key || (key != null && key.equals(k))))
368 return e;
369 }
370 return null;
371 }
Run Code Online (Sandbox Code Playgroud)