在mac上使用JDK 8,查看来自HashMap.java的以下代码:
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}对返回的ks的任何更改都将反映在keySet中,因为它们总是指向相同的基础集,如果这是真的,它是否可以写成:
public Set<K> keySet() {
if (keySet == null) {
keySet = new KeySet();
}
return keySet;
}这两个代码段的行为是否等效?
如果是这样的话,为什么HashMap使用第一个变体而不是第二个变体?
发布于 2020-11-20 06:14:00
对局部变量进行缓存是为了提高性能。生成的字节码较小,字段只读取一次,因此缓存丢失只能发生一次,还有其他一些事情。
这是一个相当高级的优化,应该只在非常频繁运行的代码块上进行。之所以在这里应用它,很可能是因为HashMap是用Java1.2编写的,当时JIT是非常基本的,因此类似的事情会产生相当大的影响。
在这种情况下,它也是为了支持多线程访问。HashMap不是同步的,但是如果以后不修改它,则可以通过安全发布共享它。如果两个线程同时执行该方法,则可能会出现一个争用条件:if(keySet == null)中的第一个读取可以读取另一个线程写入的更新值,而return keySet;中的第二个读取将读取旧的(null)值。使用局部变量可以确保if和return在非空时使用相同的引用。所以它永远不能返回null。
发布于 2020-11-20 06:27:53
正如@Fransesco所指出的,局部变量仅作为优化保存。在一些情况下,它还避免了新对象的创建。
该实现在内部不存储任何状态,并在基础hashmap上操作所有操作,并按照java文档的要求对集合进行更改。
不允许使用UnsupportedOperationException)
)。
供参考
/**
* Returns a {@link Set} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own <tt>remove</tt> operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
* operations.
*
* @return a set view of the keys contained in this map
*/
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}
final class KeySet extends AbstractSet<K> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<K> iterator() { return new KeyIterator(); }
public final boolean contains(Object o) { return containsKey(o); }
public final boolean remove(Object key) {
return removeNode(hash(key), key, null, false, true) != null;
}
public final Spliterator<K> spliterator() {
return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super K> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}AFAIK在所有平台上的行为都是一样的,而不仅仅是Mac。
https://stackoverflow.com/questions/64923690
复制相似问题