简体   繁体   English

从Java Servlet发送巨大的json对象

[英]Send huge json object from Java Servlet

Java servlet returns JSON object. Java servlet返回JSON对象。

response.setContentType("application/json");
response.getWriter().write(json.toString()); 

JSON object contains data fetched from table (database) size of which > 50 MB. JSON对象包含从大于50 MB的表(数据库)中获取的数据。

On running, servlet throws this error: 在运行时,servlet会引发以下错误:

java.lang.OutOfMemoryError: Java heap space

It seems the issue is while writing json data. 看来问题出在写json数据时。 Server is unable to allocate contiguous memory of size> 50 MB to the String. 服务器无法将大小大于50 MB的连续内存分配给该字符串。

I am unable to figure out fix for this issue. 我无法解决此问题。 How can I send huge JSON object from Servlet? 如何从Servlet发送巨大的JSON对象?

json.toString() is likely to cause the error. json.toString()可能导致错误。 It is creating one big string from the already existing json object before anything has been send out. 它是在发送任何内容之前从已经存在的json对象创建一个大字符串。

Slurping everything into memory is convenient, but not very wise when it comes to any limitations. 将所有内容都存储到内存中很方便,但是在遇到任何限制时并不是很明智。 Process your database records one by one and stream immediately to the client instead of copying around in memory. 处理您的数据库记录一个接一个并立即流到客户端,而不是在内存中进行复制。 Rule of thumb: "Any limitation given will be exceeded at some time." 经验法则:“有时会超出给定的任何限制。”

Splitting the JSON data structure into smaller parts is definitely one way to solve the problem at hand. 将JSON数据结构拆分成较小的部分绝对是解决当前问题的一种方法。 But an alternative via heap size increase might do the job in this case as well. 但是在这种情况下,通过增加堆大小的替代方法也可以完成这项工作。

The “java.lang.OutOfMemoryError: Java heap space” error will be triggered when you try to add more data into the heap space area in memory, but the size of this data is larger than the JVM can accommodate in the Java heap space. 当您尝试向内存中的堆空间区域添加更多数据时,将触发“ java.lang.OutOfMemoryError:Java堆空间”错误,但是此数据的大小大于JVM在Java堆空间中可以容纳的大小。

Note that JVM gets a limited amount of memory from the OS, specified during startup. 请注意,JVM从操作系统获取的内存量有限,这是在启动期间指定的。 There are several startup parameters controlling the separate regions of memory allocated, but in your case you are interested in heap region, which you can set (or increase if present) similar to the following example setting your heap size to 1GB: 有几个启动参数可控制分配的内存的单独区域,但是在您的情况下,您对堆区域很感兴趣,可以像设置将堆大小设置为1GB的以下示例一样设置(或增加堆大小):

java -Xmx1024m com.mycompany.MyClass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM