Srujan Kumar Gulla Srujan Kumar Gulla - 1 year ago 96
Java Question

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.

Answer Source

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

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

See this answer for more info.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download