Thursday, September 9, 2010

java.lang.OutOfMemoryError with StringBuilder or StringBuffer

StringBuilder or StringBuffer are used for string manipulations. Yet they fail some times.
Both the final classes are the extension for packaged scoped abstract class named "java.lang.AbstractStringBuilder". These builder/buffer classes holds character array and append or manipulate this char[] each time we perform operations on it. The default char[] size is 16 although this can be specified while creating the object. When append() method is called upon StringBuilder/StringBuffer, the capacity of this char[] is checked if the String/char/any other object can be added to ongoing char[] buffer. If the character buffer size is less. I.e. not sufficient enough to append more, the capacity is doubled . Lets say its capacity was 16, and not sufficient to add more, than the the capacity is increased by doubling the size of current buffer length. This keeps happening when you keep on appending stuffs to it. Common case is while reading a file and storing it inside memory in form of a StringBuilder. You never know what the size of file could be. when size isn't sufficient for the StringBuilder, buffer size is doubled and this keeps growing. A point will reach when System is not able to