javaexceptionjava.lang.class

I am facing java.lang.OutOfMemoryError in webapplication for large data


I have more than 20 category in which each category contains more than 400+ subcategories in webapplication.

When I press perticular category button it throws java.lang.OutOfMemoryError. Here is java file code. In this code, I am putting subcategory data in to json object and then add it to json array.

String responceObjectStr;
JSONObject responseObject;
for(int i=0;i<category.length;i++){
    responseObject = new JSONObject();
    JSONArray ja = new JSONArray();
    responseObject.put(category[i],Categorywisedata);//adding data to response
    ja.put(responseObject);//putting response object to JSONArray
    responceObjectStr = new String(ja.toString().getBytes("UTF-8"));
    out.print(responceObjectStr);//response
    responceObjectStr = null;
    responseObject = null;
} 

Here in each category it may have 400+ subcategory. When I press the category button it shows java.lang.OutOfMemoryError.

How to solve this. I don't want to increase JVM memory for this. I want Java code solution to handle this.


Solution

  • What is out in this code?
    Is it a web application and you are posting this over http?
    You might be able to flush the output stream. If the container supports streaming the content, then it won't build up in a potential buffer causing the out of memory error.

    What line is causing the out of memory exception?

    An alternative could be to only reply with the categories and ignore the subcategories. If the client needs subcategories for one category, it can request that data. If it needs subcategories for all of them, it will have to request it multiple times.
    Yes, this will be slower, but speed and memory are often traded off with each other.