带有ArrayList的Java OutOfMemoryError <list <integer>&gt; </list <integer>

时间:2015-02-16 01:20:52

标签: java arraylist out-of-memory

我想用Java创建一个非常大的图形(大约有1000万条边)。我计划用List<List<Integer>>来描述边缘,内部List<Integer>描述每条边的两个顶点(顶点是整数类型)。

以下代码在向图表添加约100万条边后抛出OutOfMemoryError。 (为了讨论起见,我简化了边缘的生成方式。)

public static void main(String[] args) {
  List<List<Integer>> graph = new ArrayList<List<Integer>>();
  for (int i = 0; i < 10000000; i++) {
    List<Integer> edge = new ArrayList<Integer>();
    // the real edges are more complicated (than from vertex i to vertex i+1)
    // this is simplified for the sake of the discussion here
    edge.add(i);
    edge.add(i+1);
    graph.add(edge);
  }
}

我搜索了OutOfMemoryError,并且我已经将Eclipse的初始堆大小增加到2G:-Xms2g -Xmx4g -Xss2m(传递给JVM)。但这并没有解决问题。

然后我想也许我应该通过调用List<Integer> edge来垃圾收集System.gc()变量,以防它的内存没有被清除。这也不起作用。

我想也许问题出在List<List<Integer>>数据结构上。我尝试了List<int[]>,这持续了一段时间:在OutOfMemoryError发生之前添加了更多边。我现在没有更好的主意。

我一直在寻找类似的问题,但没有找到太多帮助。我想知道是否有人有这种情况的经验。

2 个答案:

答案 0 :(得分:5)

让程序使用Eclipse中的更多内存:

转到Run - &gt;运行配置。你会看到这个窗口 Run Configurations

点击Arguments Run Configurations/Arguments

输入您的VM参数 Run Configurations/Arguments/VM Arguments

答案 1 :(得分:0)

由于除了设置max heap参数之外还要使用大量RAM,因此请确保使用64位Java。 32位仅限于2 Gigs或类似的东西。

此外,对于大型图表,您应该考虑使用数据库。

最后但并非最不重要的是,也许您可​​以重新考虑您的算法,有时您不需要所有的节点和边缘。