Blogs: Leaking memory in Java

  1. Leaking memory in Java (2 messages)

    The common line of thought is that the Java Garbage Collector will take care of cleaning up behind you. This is of course totally true in all normal cases. But sometimes, the Garbage Collector can't clean up, because you still have a reference, even though you didn't know that. public class TestGC { private String large = new String(new char[100000]); public String getSubString() { return this.large.substring(0,2); } public static void main(String[] args) { ArrayList subStrings = new ArrayList(); for (int i = 0; i <1000000; i++) { TestGC testGC = new TestGC(); subStrings.add(testGC.getSubString()); } } } Now, if you run this, you'll see that it crashes with something like the following stacktrace: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.lang.String.(String.java:174) at TestGC.(TestGC.java:4) at TestGC.main(TestGC.java:13) Why does this happen? We should only be storing 1,000,000 Strings of length 2 right? That would amount to about 40Mb, which should fit in the PermGen space easily. So what happened here? Let's have a look at the substring method in the String class.
    Read the complete post : http://blog.xebia.com/2007/10/04/leaking-memory-in-java/

    Threaded Messages (2)

  2. I don't know which version of the JVM this is trying to use as an example but when java constructs a new string using this constructor: String(char value[], int offset, int count) It sets the value using this: this.value = Arrays.copyOfRange(value, offset, offset+count);
  3. Garbage example[ Go to top ]

    That is expected and sensible behaviour, especially since the same segment of the string was picked, copying the string array would be MUCH more expensive in memory. If you need to work with such huge strings, rethink your approach e.g. by using buffer windowing, Java 1.5 or Java 1.6 StringBuffer/StringBuilder to hold large strings, allocate more memory for Java, or use an embedded database to hold the segments! Seriously, 100000 chars is not a large array, far more bytes were used by the massive ArrayList!