Thursday, 13 June 2019

Core Java | Memory leak in JDK 1.6 substring method?


How does substring() method work in JDK 1.6

String in Java is a sequence of characters (maintained in char array value[]). The 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. Yes, you heard it correct. Memory leak.



If you have a VERY long string and need a small part each time by using substring() method, this will return the offset and count which refers to the original string array which will not permit to garbage collection of original string array. Example, you require the first 2 characters from the 10 MB size string, the Java 1.6 substring method will not garbage collect the Original string that is of 10 MB and not in use.

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 points to an 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, a new string will form in the constant pool with new char value[] array and we can overcome the problem of garbage collection of an old string array.


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...