Wednesday, 28 October 2015

Memory leak in JDK 1.6 substring method

How does substring() method works in JDK 1.6

String in java is a sequence of characters (maintained as char array value[]).

String is more like a utility class which works on that character sequence.

private final char value[];

/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;

These two private variables (offset and count) used to manage the char array.

When we create a substring of String using substring() method, this method assigns the new values of offset and count variables every time.

Problem with above approach till JDK 1.6 (Memory leak)

If you have a VERY long string, but we only need a small part each time by using substring(). substring() method will return the offset and count which refers the original string array which will not permit to garbage collection of original string array.

This will cause a performance problem, since we need only a small part and keeping the whole char value[] array (No garbage collection).

    public String substring(int beginIndex, int endIndex) {
     //check boundary
return ((beginIndex == 0) && (endIndex == count))?this :
  new String(offset + beginIndex, endIndex - beginIndex, value);
    }

    String(int offset, int count, char value[]) {
this.value = value;
     this.offset = offset;
     this.count = count;
    }

Resolve the memory leak in JDK 1.6

subString = string.substring(3, 10) + "";

In above code, the string.substring(3, 10) will return the substring which point to original string array and the substring will not allow the garbage collection for old string (char value[]).

But when we add the empty string to offset, new string will form in constant pool with new char value[] array and we can overcome the problem of garbage collection of old string array.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...