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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With