簡體   English   中英

在讀取 Java 中的巨大 Json 響應時,超出 Memory

[英]Out of Memory while reading Huge Json response in Java

My requirement is to read Huge Json from REST API call and process, i googled a lot to find out a feasible solution, everyone saying use JsonReader bypassing InputStream.I am doing the same but still encountered out of memory.

我正在使用 gson 庫來獲取數據,我不確定如何實現此功能,請您指導我。 小 json 響應,這工作正常且快速,同時獲得巨大響應

public void processHugeInputStream(InputStream is){
 BufferedReader br = new BufferedReader(new InputStreamReader(is));
 String line;
 List<Sample> list = new ArrayList<Sample>();
 while(line = br.readLine()!=null){
 Reader stringReader = new StringReader(line);
 JSONReader reader = new JSONReader(stringReader);
 reader.setLinent(true);
 Sample object = gson.fromJSON(reader,Sample.class);
 list.add(object);
}
}

看起來您正在逐行閱讀 stream,這沒關系。

但是,您正在分配一個List ,然后將每個解析結果添加到列表中,因此,如果您有一個巨大的 Json 輸入 stream 您最終將得到一個巨大的已解析對象列表。 這可能是給你 memory 錯誤的部分。

If you have a way of refactoring the code so that you can process each Json Object as it comes in, rather than adding them all to an array and processing later, then you can run without needing to increase the memory size of the JVM.

使這個通用的一種方法是讓一個Consumer<Sample> function 傳遞給這個方法,然后你可以accept每個Sample進來。

請在 Java 中增加您的堆大小。 將此選項與您的 Java 命令一起使用: java -Xmx6g...增加到 6 GB

還有更多選項可以配置您的 memory 用法:

  • 線程堆棧大小 -Xss128m - 將線程堆棧大小設置為 128 兆字節。
  • 年輕代大小 -Xmn256m - 將年輕代大小設置為 256 兆字節。

在這里,您可以獲得該主題的完整文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM