Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String.substring method potential memory leak?

I was going through the String class API and looks like there is a potential memory leak caused by substring method as it shares same character array as original String.

If original string is huge then small string returned by substring can prevent original string(backed up by large array) from garbage collection in Java.

Any thoughts or did I read the API wrong.

like image 933
Srujan Kumar Gulla Avatar asked Jan 04 '13 16:01

Srujan Kumar Gulla


People also ask

How does the substring () method of string class create memory leaks?

In the String object, when you call substring , the value property is shared between the two strings. So, if you get a substring from a big string and keep it for a long time, the big string won't be garbage collected. It could result in a memory leak, actually.

Can strings cause memory leaks?

No, String assignment, by itself does not create anything. The only thing resembling a "leak" in Java is when you put a whole bunch of references into some array or other structure and then forget about it -- leave the structure "live" (accessible) but don't use it.

How does substring () inside string works?

The substring(int beginIndex, int endIndex) method of the String class. It returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

Does substring method create a new object?

Even your substring calls won't create new string objects in the pool, it will use the existing "Hello World" one, but in this case it will only use characters from position 0 to 3 for your first call to substring, for example. Starting from Java 7, substring will not share the characters, but will create a new one.


1 Answers

There is a potential for a memory leak, if you take a substring of a sizable string and not make a copy (usually via the String(String) constructor).

Note that this has changed since Java 7u6. See https://bugs.openjdk.java.net/browse/JDK-7197183.

The original assumptions around the String object implementing a flyweight pattern are no longer regarded as valid.

See this answer for more info.

like image 113
Brian Agnew Avatar answered Sep 25 '22 13:09

Brian Agnew