How substring method creates memory leak in Java


How substring() method of String class use to create memory leaks before Java 7?

We know memory leak happens when any object is not used by the application and also GC is unable  to reclaim memory blocked by that object, in that situation we would have Memory leak problem.

Calling substring method creates scenario as described above which leads to Memory leak.

public class SubstringExample {
    public static void main(String[] args) {
        String str1 = "Hello, this is Java";
        String str2 = str1.substring(7, 11);
        System.out.println(str2);
    }
}

Below diagram may give some clarity on how substring() method causes Memory leak.

What happens when we call "str1.substring(7, 11);", Ideally what should happen is, str2 should hold the value "this" but that is not happening and it still points to original string referenced by str1.

Before Java 7, String class uses count, offset and value field for representing any String.
count = length of the String
offset = index from which string needs to be printed
value = holds the actual String

String str1 = "Hello, this is Java";
count = 19
offset = 0
value = "Hello, this is Java"

Now when we print str1, it refers string present in value and start printing from index mentioned in offset which is 0 and print 19 characters from that index, which is a complete string.

String str2 = str1.substring(7, 11);
count = 4
offset = 7
value = "Hello, this is Java"

Now when we print str2, it refers string present in value and start printing from index mentioned in offset which is 7 and print 4 characters from that index, which is "this".

Note: str2 holds the value string "Hello, this is Java" which is not at all required, instead it should store "this".
Basically, str2 still points to the same string referenced by str1, because of which even str2 needs small portion of the string "this" but big string "Hello, this is Java" will not be garbage collected as str2 is holding it.

In Java 1.7 version, offset and count variable which is used to track position of the string to print are removed from String class to prevent memory leak.

You may also like to see


Given an array of integers. All numbers occur thrice except one number which occurs once. Find the number in O(n) time & constant extra space. 

Count number of Bits to be flipped to convert A to B 

Count number of Set Bits in Integer. 

Check if number is Power of Two. 

Find all subsets of a set (Power Set). 

Skyline Problem in Java. 

Find Minimum length Unsorted Subarray, Sorting which makes the complete array sorted 

Count trailing zeros in factorial of a number 

When to use SOAP over REST Web Service. Is REST better than SOAP? 

Tower Of Hanoi Program in Java. 

Post a Comment