Two Laptop Bag
The moose likes I/O and Streams and the fly likes StringBuilder out of memory error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "StringBuilder out of memory error " Watch "StringBuilder out of memory error " New topic

StringBuilder out of memory error

Joshua Elkino
Ranch Hand

Joined: Jul 24, 2007
Posts: 91
I'm going crazy because i'm getting the following error and i can't figure out why.

java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(
at java.lang.AbstractStringBuilder.expandCapacity(
at java.lang.AbstractStringBuilder.append(
at java.lang.StringBuilder.append(

my code is

Line 37 is the append line. What am i doing wrong? I tried to put a sysout before the append to see what characters are being sent to my servlet post, but there is nothing in the logs. This happens even after i restart tomcat and there is nothing hitting the servlet.

Poobhathy Kannan
Ranch Hand

Joined: May 26, 2004
Posts: 94
Because, you can see from the error message, the JVM does a arrayCopy when it expands the StringBuilder. If the StirngBuilder needs to be expanded whenever you append a char, then JVM will do this array copy again and again which consumes a lot of memory. I think you need to change your way of reading with buffering. try using readLine(byte[] b,int off,int len) method of ServletInputStream.
Joe Ess

Joined: Oct 29, 2001
Posts: 9189

JavaRanch FAQ: Investigate OutOfMemoryError

[How To Ask Questions On JavaRanch]
I agree. Here's the link:
subject: StringBuilder out of memory error
It's not a secret anymore!