Guava Multimap putAll OOM?

近日使用ArrayListMultimap的putAll时犯了一个错误,先看一下Code,Pos1、2、3、4输出什么值?

//test1
Set<Long> sets = new HashSet<>();
sets.add(1L);
sets.add(2L);

Multimap<String, Long> maps = ArrayListMultimap.create();

maps.putAll("A", sets); // ①
System.out.println("Pos1:" + maps.get("A").size());

maps.putAll("A", sets); // ②
System.out.println("Pos2:" + maps.get("A").size());

// test2
Multimap<String, Long> maps2 = ArrayListMultimap.create();

maps2.put("A", 1L);
maps2.put("A", 2L);
System.out.println("Pos3:" + maps2.get("A").size());

maps2.put("A", 1L);
maps2.put("A", 2L);
System.out.println("Pos4:" + maps2.get("A").size());

结果如下:

Pos1:2
Pos2:4

Pos3:2
Pos4:4

这里的putAll,不是覆盖相同key的value,而是追加;putAll或put,对同一key下相同的value并不会过滤。这里和map.put(k,v)是不一样的。所以,如果重复调用ArrayListMultimap的putAll或put方法,value就会造成OOM的异常,这里要特别注意。

下面,我们从源码进行一次分析:

public boolean putAll(@Nullable K key, Iterable<? extends V> values) {
  checkNotNull(values);
  // make sure we only call values.iterator() once
  // and we only call get(key) if values is nonempty
  if (values instanceof Collection) {
    Collection<? extends V> valueCollection = (Collection<? extends V>) values;
    return !valueCollection.isEmpty() && get(key).addAll(valueCollection); // ① 
  } else {
    Iterator<? extends V> valueItr = values.iterator();
    return valueItr.hasNext() && Iterators.addAll(get(key), valueItr);
  }
}

下面看下addAll方法①:

public boolean addAll(Collection<? extends V> collection) {
  if (collection.isEmpty()) {
    return false;
  }
  int oldSize = size(); // calls refreshIfEmpty
  boolean changed = delegate.addAll(collection); // ②
  if (changed) {
    int newSize = delegate.size();
    totalSize += (newSize - oldSize);
    if (oldSize == 0) {
      addToMap();
    }
  }
  return changed;
}

其中addAll方法②调用了java.util.ArrayList的addAll:

public boolean addAll(Collection<? extends E> c) {
    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacityInternal(size + numNew);  // Increments modCount
    System.arraycopy(a, 0, elementData, size, numNew);
    size += numNew;
    return numNew != 0;
}

至此,ArrayListMultimap的putAll是调用了java.util.ArrayList的addAll。我们还记得list.add(v)方法:

List<Long> lists = new ArrayList<>();
lists.add(1L);
lists.add(1L);
lists.add(1L);
System.out.println("Pos1:" + lists.size());

List<Long> list2 = new ArrayList<>();
list2.addAll(lists);
list2.addAll(lists);
System.out.println("Pos2:" + list2.size());

结果如下:

Pos1:3
Pos2:6
上一篇:读《演进式架构》学习笔记


下一篇:Android笔记:如何解决java中的setPeekHeight()没有给出与xml中相同的结果?