可怕的表现&Java 8 构造函数引用的大堆内存占用? [英] Horrendous performance & large heap footprint of Java 8 constructor reference?
问题描述
我刚刚在我们的生产环境中遇到了相当不愉快的经历,导致 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;
程序不会失败,但会一直冲击直到被杀死(索引很容易达到 150 万).
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[]
元素,导致 OutOfMemoryError
如此之快?
Why does ArrayList::new
create so many Object[]
elements on the heap that it causes OutOfMemoryError
so fast?
(顺便说一句 - 当集合类型为 HashSet
时也会发生这种情况.)
(By the way - it also happens when the collection type is HashSet
.)
推荐答案
在第一种情况 (ArrayList::new
) 中,您使用的是 constructor 它接受一个初始容量参数,在第二种情况下你不是.较大的初始容量(代码中的index
)会导致分配较大的Object[]
,从而导致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 OutOfMemoryError
s.
以下是两个构造函数的当前实现:
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.
这篇关于可怕的表现&Java 8 构造函数引用的大堆内存占用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!