我刚刚在我们的生产环境中遇到了相当不愉快的经历 OutOfMemoryErrors: heapspace..
我将这个问题追溯到我ArrayList::new在函数中的使用.
要通过声明的构造函数(t -> new ArrayList<>())验证这实际上比正常创建更糟糕,我编写了以下小方法:
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
运行方法newMethod=true;将导致方法OutOfMemoryError在索引达到30k后失败.随着newMethod=false;程序不会失败,但一直冲击直到被杀(索引容易达到150万).
为什么在堆上ArrayList::new创建如此多的Object[]元素会导致OutOfMemoryError如此之快?
(顺便说一下 - 当集合类型出现时也会发生HashSet …