2016-09-26 80 views
-2

我寫了一段代碼。我面臨的問題是,當for循環的「j」超過1000時,我開始出現「GC超出限制」的錯誤。如果我將分配的內存增加到4GB,我可以迭代到2000年之後出現相同的問題。我想保留這個增加內存的選項作爲最後的手段,並且想要嘗試擴展我的代碼。編譯器強調了我放置箭頭的語句的問題。 有人可以請指導我,這可能是可能的錯誤。 我已經訪問過這個問題Error java.lang.OutOfMemoryError: GC overhead limit exceeded代碼中超出了GC開銷限制

 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

地方你清楚'ls2d'在你的代碼? –

+0

是使用ls2d。我只粘貼了編譯器突出顯示的那部分代碼。 – Shahzaib

+0

'list1'已經很大了,所以如果你花時間把它添加到'ls2d'而不清除它,它會很快佔用很多內存,導致Omega –

回答

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 
+0

我做了這些更改,錯誤仍然存​​在 – Shahzaib

+0

@Shahzaib - OOM發生了什麼變化? –

+0

是的,現在這是一個Java堆空間錯誤,出現在我粘貼 – Shahzaib

0

這裏有一對夫婦的想法,以減少內存消耗 - 和運行時可能。

  • 使用,而不是一個ArrayList數組 - 你似乎沒有使用ArrayList特定功能,這樣的陣列將更加緊湊,更容易與
  • 告訴拆分工作只是讀取一行的第一個字段

請注意,我刪除了所有旨在強制清理垃圾回收器的代碼,我不認爲這有助於解決此問題。


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 
} 
相關問題