有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java OutOfMemoryError与ArrayList<List<Integer>>

我想用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:-Xms2g -Xmx4g -Xss2m(传递给JVM)的初始堆大小增加到2G。但这并没有解决问题

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

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

我到处寻找类似的问题,但没有找到多少帮助。我想知道是否有人有过这种经历


共 (2) 个答案

  1. # 1 楼答案

    由于除了设置max heap参数外,还使用了大量RAM,因此请确保使用64位Java。32位限制为2个Gig或类似的大小

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

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

  2. # 2 楼答案

    要让您的程序使用Eclipse提供的更多内存,请执行以下操作:

    转到运行->;运行配置。你会看到这扇窗户 Run Configurations

    点击参数 Run Configurations/Arguments

    向VM输入参数 Run Configurations/Arguments/VM Arguments