I found that using String.substring
is known for memory issues related to String.split
.
Is there a memory leak in using String.split
?
If yes what is the work-around for it?
Following link show correct usage of substring in Java.
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4513622
One more blog which talk about possible MLK in substring.
http://nflath.com/2009/07/the-dangers-of-stringsubstring/
If we read a massive String object, and call intern() on that object, it goes to the string pool, which is located in PermGen (permanent memory), and will stay there as long as our application runs. This blocks the memory and creates a major memory leak in our application.
Use reference objects to avoid memory leaks Using the java. lang. ref package, you can work with the garbage collector in your program. This allows you to avoid directly referencing objects and use special reference objects that the garbage collector easily clears.
Java Memory Leaks – Basic concept A Memory efficient program consumes as little memory as possible during the operation. Memory leaks are unusual in the case of memory-efficient programs. The Java Garbage Collector does the job of freeing up memory occupied by unused objects in the program.
Unclosed Resources Such code requires opening a stream, connection, or file inside our code. But we have to remember that we are the ones responsible not only for opening the resource but also for closing it. Otherwise, our code can leak memory, eventually leading to OutOfMemory error.
Update: Behavior has changed in 1.7.0_06: See this article: Changes to String internal representation made in Java 1.7.0_06 at java-performance.info.
As pointed out by @finnw there is indeed kind of a memory leak lurking around when using String.substring
. The reason is that String.substring
only returns a view of a portion of the given string, i.e., the underlying string is still kept in memory.
To force the creation of a new string, unrelated to the source, you'll have to use the new
keyword. I.e., you'll have to do for instance
String[] parts = orig.split(";");
//String mySubstring = parts[i]; // keeps orig from being GC'd
String mySubstring = new String(parts[i]); // creates a new string.
or, perhaps more direct
String mySubstring = new String(orig.split(";")[i]);
I must say that this behavior seems "unnecessary" to me. It should be solvable using weak references or some other technique. (Especially considering that String
is already a special class, part of the Java language specification.)
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