Thursday, 13 June 2019

Core Java | How substring memory leak fixed in JDK 1.7?

Resolve the memory leak in JDK 1.7

substring() method implementation in JDK 1.6

Substring and the original string represents the same Character array which leads to a memory leak.

    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;

substring() method implementation in JDK 1.7

This problem fixed in the JDK 1.7 by returning the new copy of character array.

    public String(char value[], int offset, int count) {

          //check boundary
          // It return new copy on array.
          this.value = Arrays.copyOfRange(value, offset, offset + count);


    public String substring(int beginIndex, int endIndex) {

          //check boundary
          int subLen = endIndex - beginIndex;

          return new String(value, beginIndex, subLen);


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...