Memory leak traps in the Java Standard API

A big one is that getting substrings of Java strings refers to the original string.

Example: you read in a 3000 character record and get a substring of 12 characters, returning that to the caller (within the same JVM). Even though you don’t directly have a reference to the original string, that 12 character string is still using 3000 characters in memory.

For systems that receive and then parse lots of messages, this can be a real problem.

You have a couple of ways to avoid this:

String sub = new String(str.substring(6,12));

or

String sub = str.substring(6,12).intern();

The first is more clearcut. The second has other implications because you’re using PermGen space. Overused you could run out unless you give your VM enough.

Remember this is only relevant if you’re taking small substrings and then throwing away the original string and you’re doing this a lot.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)