作者killeryagami (kira)
看板java
標題Re: [問題] Java heap space (已爬文)
時間Tue Nov 24 18:43:20 2009
※ 引述《killeryagami (kira)》之銘言:
: JVM能吃的Memory有限,所以我有幾個問題想請教各位神人
: 平常在程式撰寫的時候,都用什麼方式節省記憶體?
: 再者是我的一部份程式碼,用途是讀取頁面原始碼
: public String getHtmlCode(String url,String encode)throws IOException{
: StringBuffer sb = new StringBuffer();
: if(checkUrl(url)){ //這個地方是判斷是不是我要的網頁
: try {
: toConnection(url);
: br = new BufferedReader(new InputStreamReader(urlConn.
: getInputStream(), encode));
: int count = 0;
: String line = "";
: while ((line = br.readLine()) != null && count<= 700 ) {
: //為了不讓資料過大,所以只讀取700行的原始碼
: sb.append(line.intern());
: count++;
: }
: br.close();
: toDisconnect();
: } catch (Exception e) {
: System.out.println("Paser: " + e);
: }
: this.htmlcode = sb.toString();
: }
: return this.htmlcode;
: }
: 我的Project出現Java heap space的問題,目前懷疑是這部份的程式碼
: 在程式離開這個method之後,htmlcode是否會立即被回收(釋放空間)?
: 又例如
: String htmlcode = getPageHtml(url_1);
: htmlcode = getPageHtml(url_2);
: 那麼JVM中原本儲存的700行url_1的資料,是不是不會被馬上釋放?
: 最近對於節省記憶體有點頭大,希望各位多多指教 m(_ _)m
/**
按照T大以及其他人的建議,找出問題位置
我想抓的資料形式是有分頁,因此以迴圈方式不斷抓分頁資料,直到分頁不存在為止
錯誤訊息還是只有一行 Java heap space ......
*/
public ArrayList<String> crawlerLeafData()
{
ArrayList<String> alLeafData = new ArrayList<String>();
String html="";
for (int i = 1; ; i++) {
String nextPageUrl = "
http://mypage/List.jsp?ShowPage="+i; //資料
有分頁
try{
html = pas.getHtmlCode(nextPageUrl, "Big5");
if (!checkLeafDataExist(html)) //若分頁i已經沒有想抓的資料或
不存在
break;
}catch(Exception e){System.out.println("LeafError: "+e);}
ArrayList<String> PageAry = pas.getHtmlArray(html); //抓取某個Tag,
是Url的參數
for (int j = 0; j < PageAry.size(); j++) {
String tempUrl =
"
http://mypage/hello/List.jsp?"+PageAry.get(j);
allLeafData.add(tempUrl);
}
}
return alLeafData;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.109.18.52
推 PsMonkey:你的問題,出在更基本的問題。想清楚流程跟需要性 11/24 20:23
※ 編輯: killeryagami 來自: 140.109.18.52 (11/25 10:10)
→ killeryagami:是...讀取原碼太多次嗎?不太懂... 11/25 10:14
推 tcw026:最好用finally把inputsream close掉. 11/25 21:31
推 ynchang:請用JRE 6的環境跑看看..會顯示OutOfMemory的相關資訊 11/25 22:50
→ xlk:呼叫這個函式的程式做了些什麼?真的有把allLeafData處理掉? 11/26 15:39
→ jej:用ByteArrayInputStream??用byte[]接真的超過heap就掛不用談.. 11/27 22:01