1

I am facing java.lang.OutOfMemoryError: Java heap space. Some bulk amount of data converting into toString(). I have my own implementation of toString code. You can see below code:

String dataStr = (new LargeData(objData)).toString();

public String toString() 
{ 
    try 
    { 
       if (localBase64Binary != null) 
       { 
           ByteArrayOutputStream out = new ByteArrayOutputStream(); 
           localBase64Binary.writeTo(out); return out.toString("utf-8"); 
       } 
     } 
    catch (IOException ex) 
    { 
       ex.printStackTrace(); 
    } 
    return null; 
}

I am using maximum heap space -Xms128m -Xmx256m. If I increase heap space just I can postpone out of memory some days only. Is there any way to optimize the code in this situation?

Can any one please guide me or help me to resolve this issue?

4
  • Please check my toString code below public String toString() { try { if (localBase64Binary != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); localBase64Binary.writeTo(out); return out.toString("utf-8"); } } catch (IOException ex) { ex.printStackTrace(); } return null; } Commented Aug 4, 2012 at 3:43
  • 1
    Please edit your post to include the code. Commented Aug 4, 2012 at 3:45
  • @user Please post the code in question only and use {} tags present in the editor window to format the code. Commented Aug 4, 2012 at 3:49
  • 1
    What is a localBase64Binary? Commented Aug 4, 2012 at 3:53

2 Answers 2

3

One problem is dynamically resizing arrays to add more elements. This requires allocating a new array larger than the existing array and then copying the elements. If the new array is larger than half the heap space it is guaranteed to fail.

The solution to your problem is to not use .toString(). Instead of trying to keep all the data in RAM, pass a file stream to the method and write the data to disk (or stream it to a socket, or a pipe).

Sign up to request clarification or add additional context in comments.

Comments

1

In stead generating a large string and passing to something else to do something with, you need to process the data produced as you generate it.

e.g. instead of

String dataStr = (new LargeData(objData)).toString();
out.println(dataStr);

do

new LargeData(objData).writeTo(out);

as this will use much less memory at once.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.