Thursday, July 7, 2011

Java memory leak caused by String object

For some reason, I recall that Java String can easily cause memory leak. Since it has not been fixed in JVM, I write this note to keep it in mind. Next time, I will write down C/C++ and C# memory leak on pocket PC, which I was experienced.

We all know that Java has garbage collector, which automatically release memory of object if there is refernece points to it any more. However, something strange from String class happens in at least Sun and IBM's JVM. String is definietly frequently used Object in Java program. So, it will be significant if its function causes memory leak. The souce of the issue is from substring function of String class in JVM implementations from Sun and IBM at least. Speak in simple way, substring() function will not create a new String object having its own memory block and return it. It will only create a String object, which points to part of original String object. Therefore, the memory block occupied by original String object will be refered by new sub String object too. This will cause siginificant memory leak problem if original String is very long and the sub String object will be used outside scope where original String object residents. Below figure gives a clear view of this statement.

To workaround this issue, we can use new operator to force the sub String object has its own memory block. In fact, this is reported as a bug in Sun microsystem. But, it has low priority and has not been fixed. There is an interesting discussion about Java memory leak here: Creating a memory leak with Java

No comments:

Post a Comment