可怕的性能Java 8构造函数引用的大堆占用空间?

问题描述:

我只是在我们的生产环境中有一个相当不愉快的经历,导致 OutOfMemoryErrors:heapspace ..

I just had a rather unpleasant experience in our production environment, causing OutOfMemoryErrors: heapspace..

跟踪问题,我使用 ArrayList :: new 在一个函数。

I traced the issue to my use of ArrayList::new in a function.

要验证这是实际执行通过声明的构造函数( t - > new ArrayList<>())比正常创建更糟糕,我写了以下小方法:

To verify that this is actually performing worse than normal creation via a declared constructor (t -> new ArrayList<>()), I wrote the following small method:

public class TestMain {
  public static void main(String[] args) {
    boolean newMethod = false;
    Map<Integer,List<Integer>> map = new HashMap<>();
    int index = 0;

    while(true){
      if (newMethod) {
        map.computeIfAbsent(index, ArrayList::new).add(index);
     } else {
        map.computeIfAbsent(index, i->new ArrayList<>()).add(index);
      }
      if (index++ % 100 == 0) {
        System.out.println("Reached index "+index);
      }
    }
  }
}

使用 newMethod = true; 的方法将导致该方法失败,并在索引命中30k后出现 OutOfMemoryError 。使用 newMethod = false; 程序不会失败,但会一直冲击直到被杀死(索引容易达到1.5百万)。

Running the method with newMethod=true; will cause the method to fail with OutOfMemoryError just after index hits 30k. With newMethod=false; the program does not fail, but keeps pounding away until killed (index easily reaches 1.5 milion).

为什么 ArrayList :: new 在堆上创建这么多 Object [] c $ c> OutOfMemoryError 这么快?

Why does ArrayList::new create so many Object[] elements on the heap that it causes OutOfMemoryError so fast?

(顺便说一下,当集合类型 HashSet c>。

(By the way - it also happens when the collection type is HashSet.)

/ code>)您正在使用构造函数它接受一个初始容量参数,在第二种情况下你不是。大的初始容量(你的代码中的 index )会导致一个大的 Object [] 被分配, code> OutOfMemoryError s。

In the first case (ArrayList::new) you are using the constructor which takes an initial capacity argument, in the second case you are not. A large initial capacity (index in your code) causes a large Object[] to be allocated, resulting in your OutOfMemoryErrors.

这两个构造函数的当前实现:

Here are the two constructors' current implementations:

public ArrayList(int initialCapacity) {
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity];
    } else if (initialCapacity == 0) {
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
}
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

类似的情况发生在 HashSet ,除非在调用 add 之前不分配数组。

Something similar happens in HashSet, except the array is not allocated until add is called.