[英]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. 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.
I am using gson library to get the data, I am not sure how to achieve this functionality, could you please guide me on this.我正在使用 gson 库来获取数据,我不确定如何实现此功能,请您指导我。 small json response, this is working fine and fast whereas getting huge response stream I am getting out of Memory.
小 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);
}
}
It looks like you are reading the stream line by line, which is ok.看起来您正在逐行阅读 stream,这没关系。
However you are allocating a List
and then adding each parsed result into the list, so if you have a huge Json input stream you will end up with a huge list of parsed objects.但是,您正在分配一个
List
,然后将每个解析结果添加到列表中,因此,如果您有一个巨大的 Json 输入 stream 您最终将得到一个巨大的已解析对象列表。 It's probably this part that is giving you the memory error.这可能是给你 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. 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.
One way you can make this generic is to have a Consumer<Sample>
function that you pass into this method, and then you can accept
each Sample
as it comes in.使这个通用的一种方法是让一个
Consumer<Sample>
function 传递给这个方法,然后你可以accept
每个Sample
进来。
Please increase your heap size in Java.请在 Java 中增加您的堆大小。 Use this option with your Java command:
java -Xmx6g...
to increase to 6 GB将此选项与您的 Java 命令一起使用:
java -Xmx6g...
增加到 6 GB
There are also more option to config your memory usage:还有更多选项可以配置您的 memory 用法:
Here you can get a full documentation to this topic在这里,您可以获得该主题的完整文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.