how can I manage to have the JVM leak memory? some ways -visible to the JVM- are: - making a thread live long and hold strong references to objects - making static references to objects some ways -invisible to the JVM- are: - writing native code that allocates memory without deallocating it - using databaseconnections, statements and resultsets without closing them another way: - using a JVM or third-party component that leaks memory for you more ideas on how to leak memory? [ March 03, 2004: Message edited by: Ronny Chan ] [ March 03, 2004: Message edited by: Ronny Chan ]
I'm not sure what you mean by "leak memory", but one I've seen before is to allocate an ever-bigger objects. Note that this is subtly different from allocating a large object and forgetting to release it. Here's an example I encountered once (in someone else's code, thank goodness). First, the perfectly sensible version of the function:
The code uses a static variable to store a string of spaces which is grown (exponentially) to make it long enough for any padding needed. Unfortunately, a collegue of mine tried to write this code but made a mistake. Instead of growing SPACES only when necessary, he grew it every time:
So every time that padWithSpaces() was called, the static variable SPACES grew... and it grew fast. Had the growth been linear instead of exponential, we might not have noticed the bug! -- Michael Chermside
This one caused me problems a few years ago: Creating Threads but not starting them - all new Threads go into a ThreadGroup, so even if your program drops the reference, it is still there. and of course there is always: linking event listeners to elements in GUI dialogs and neglecting to unlink when the dialog is closed. Bill
posted 16 years ago
Thanks to another forumposter I found out that using java.io.File.deleteOnExit() in conjunction with a webserver may result in a memory leak since the JVM exits when the webserver is stopped or restarted. Meanwhile the JVM collects information about files that can be deleted, ergo memory gets filled. Of course if you don't use deleteOnExit() often in your webapps, it shouldn't be a problem, but keep this behaviour in mind though.
A classic recepie for memory leak is to add an object to a collection whose lifetime is longer than that of the object itself. A common example is a cache. You create a new object, add it to a container, and null the reference to the object (or allow it to go out of scope), and you may think that GC will take care of the rest. But if the container is still alive, your object is still reachable and will not be garbage collected. Here is some code (as can be seen from the output, it leaks about 4Mb of memory):