substring method in String class causes memory leak [duplicate]

In past versions of the JDK, the implementation of the substring method would build a new String object keeping a reference to the whole char array, to avoid copying it. You could thus inadvertently keep a reference to a very big character array with just a one character string. Here’s an example of a bug this could induce.

This method has now been changed and this “leak” doesn’t exist anymore.

If you want to use an old JDK (that is older than OpenJDK 7, Update 6) and you want to have minimal strings after substring, use the constructor taking another string :

String s2 = new String(s1.substring(0,1));

As for your second question, regarding ” other things which can causes of memory leak in java”, it’s impossible to answer in a constructive way. There aren’t in java standard libs many instances of cases where you could so easily keep hidden references to objects. In the general case, pay attention to all the references you build, the most frequent problems probably arising in uncleaned collections or external resources (files, database transactions, native widgets, etc.).

Leave a Comment