我写了一段代码。我面临的问题是当" j"对于for循环超过1000我开始得到错误" GC开销限制超过"。如果我将分配的内存增加到4GB,我可以迭代到2000,之后会出现同样的问题。我想保留这个增加内存的选项作为最后的手段,并希望尝试扩展我的代码。编译器突出显示了我放置箭头的语句的问题。 有人可以指导我,这可能是错误。 我已经访问了这个问题Error java.lang.OutOfMemoryError: GC overhead limit exceeded
for (int j=1; j<=num_doc; j++) {
List<Integer> list1 = new ArrayList<Integer>(Collections.nCopies(129039, 0));
BufferedReader fl = new BufferedReader(new FileReader(dataFolder+"file"+ " ("+j+")"+".int"));
String line1;
while((line1=fl.readLine()) != null) {
String[] arr=line1.split(" ");//<---------------------
line1="";
int k = Integer.parseInt(arr[0]);
Arrays.fill(arr, "");
numb=numb+1;
int temp=(list1.get(k))+1;
list1.set(k, temp);
}
F_d.add(numb);
numb=0;
fl.close();
ls2d.add(new ArrayList<Integer>(list1));//<---------------------
list1.clear();
}
答案 0 :(得分:0)
可以立即优化两件事,以减少内存需求:
// we don't need all the fragments, taking only the first is fine
String firstElem=line1.substring(0, line1.indexOf(" "));
line1=null;// let GC collect this at its convenience
int k = Integer.parseInt(firstElem);
然后
// Don't add the copy, add list1 itself
// You are initing list1 in the beginning of the for cycle anyway
// and until then nothing happens.
ls2d.add(list1);//<---------------------
// list1.clear(); -- since we added list1, we don't clear it anymore
答案 1 :(得分:0)
这里有一些减少内存消耗的想法 - 可能是运行时。
请注意,我删除了所有旨在强制垃圾收集器进行清理的代码,在这种情况下我不认为它会有所帮助。
for (int j=1; j<=num_doc; j++) {
int[] list1 = new int[129039];
BufferedReader fl = new BufferedReader(new FileReader(dataFolder+"file"+ " ("+j+")"+".int"));
String line1;
while((line1=fl.readLine()) != null) {
String[] arr=line1.split(" ",2); // Just read first field - see String Javadoc
int k = Integer.parseInt(arr[0]);
list[k]=list[k]+1;
numb=numb+1;
}
F_d.add(numb);
numb=0;
fl.close();
ls2d.add(list1);// you'll obviously need to change ls2d's type, or reconvert using Arrays.asList
}