40
votes

Possible Duplicate:
Creating a memory leak with Java

What's the easiest way to cause a Java memory leak?

9
Are you looking for a contrived example or a very common programming mistake?mikerobi
a contrived example would be best please.Paul McKenzie
A memory leak is created whenever an object that is not intended to be used has a reference to it. Almost any program one could write would be a contrived example of a memory leak.OrangeDog
Take a look at 'Creating a memory leak with java' for other ways different than the easiest.Alberto

9 Answers

34
votes

You cannot really "leak memory" in Java unless you:

  • intern strings
  • generate classes
  • leak memory in the native code called by JNI
  • keep references to things that you do not want in some forgotten or obscure place.

I take it that you are interested in the last case. The common scenarios are:

  • listeners, especially done with inner classes
  • caches.

A nice example would be to:

  • build a Swing GUI that launches a potentially unlimited number of modal windows;
  • have the modal window do something like this during its initialization:
    StaticGuiHelper.getMainApplicationFrame().getOneOfTheButtons().addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    // do nothing...
    }
    })
    

The registered action does nothing, but it will cause the modal window to linger in memory forever, even after closing, causing a leak - since the listeners are never unregistered, and each anonymous inner class object holds a reference (invisible) to its outer object. What's more - any object referenced from the modal windows have a chance of leaking too.

This is why libraries such as EventBus use weak references by default.

Apart from listeners, other typical examples are caches, but I cannot think of a nice example.

16
votes

"A memory leak, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it back to the operating system." (Wikipedia)

The easy answer is: You can't. Java does automatic memory management and will free resources that are not needed for you. You can't stop this from happening. It will always be able to release the resources. In programs with manual memory management, this is different. You can get some memory in C using malloc(). To free the memory, you need the pointer that malloc returned and call free() on it. But if you don't have the pointer any more (overwritten, or lifetime exceeded), then you are unfortunately incapable of freeing this memory and thus you have a memory leak.

All the other answers so far are in my definition not really memory leaks. They all aim at filling the memory with pointless stuff real fast. But at any time you could still dereference the objects you created and thus freeing the memory → no lead. acconrad's answer comes pretty close, though as I have to admit, since his solution is effectively to just "crash" the garbage collector by forcing it in an endless loop).

The long answer is: You can get a memory leak by writing a library for Java using the JNI, which can have manual memory management and thus have memory leaks. If you call this library, your Java process will leak memory. Or, you can have bugs in the JVM, so that the JVM loses memory. There are probably bugs in the JVM, and there may even be some known ones since garbage collection is not that trivial, but then it's still a bug. By design this is not possible. You may be asking for some Java code that is affected by such a bug. Sorry, I don't know one and it might well not be a bug any more in the next Java version anyway.

11
votes

Here's a simple example

public class Finalizer {
    @Override
    protected void finalize() throws Throwable {
        while (true) {
            Thread.yield();
        }
    }

    public static void main(String[] args) {
        while (true) {
            for (int i = 0; i < 100000; i++) {
                Finalizer f = new Finalizer();
            }

            System.out.println("" + Runtime.getRuntime().freeMemory() + " bytes free!");
        }
    }
}
9
votes

Use:

public static List<byte[]> list = new ArrayList<byte[]>();

And then add (big) arrays without removing them. At some point you will run out of memory without suspecting it. (You can do this with any objects, but with big, full arrays you can run out of memory faster.)

In Java, if you dereference an object (it falls out of scope), it is garbage collected. So you have to hold a reference to it in order to have a memory problem.

3
votes
  1. Create a collection of objects at class scope
  2. Periodically add new objects to the collection
  3. Do not drop the reference to the instance of the class that holds the collection

Because there is always a reference to the collection and the instance of the object that owns the collection, the garbage collector will never clean up that memory, thus causing a "leak" over time.

3
votes

From what I've read in the most voted answer, you are most probably asking for a C-like memory leak. Well, since there's garbage collection, you can't allocate an object, lose all its references and get it still occupying memory - that would be a serious JVM bug.

On the other hand, you can happen to leak threads - which, of course, would cause this state, because you would have some thread running with its references to objects, and you may lose the thread's reference. You can still get the Thread reference through the API - see http://www.exampledepot.com/egs/java.lang/ListThreads.html

1
votes

The following extremely contrived Box class will leak memory if used. Objects that are put into this class are eventually (after another call to put to be precise... provided the same object is not re-put into it.) inaccessible to the outside world. They cannot be dereferenced through this class, yet this class ensures they cannot be collected. This is a real leak. I know this is really contrived, but similar cases are possible to do by accident.

import java.util.ArrayList;
import java.util.Collection;
import java.util.Stack;

public class Box <E> {
    private final Collection<Box<?>> createdBoxes = new ArrayList<Box<?>>();
    private final Stack<E> stack = new Stack<E>();

    public Box () {
        createdBoxes.add(this);
    }

    public void put (E e) {
        stack.push(e);
    }

    public E get () {
        if (stack.isEmpty()) {
            return null;
        }
        return stack.peek();
    }
}
0
votes

Try this simple class:

public class Memory {
    private Map<String, List<Object>> dontGarbageMe = new HashMap<String, List<Object>>();

    public Memory() {
        dontGarbageMe.put("map", new ArrayList<Object>());
    }

    public void useMemInMB(long size) {
        System.out.println("Before=" + getFreeMemInMB() + " MB");

        long before = getFreeMemInMB();
        while ((before  - getFreeMemInMB()) < size) {
            dontGarbageMe.get("map").add("aaaaaaaaaaaaaaaaaaaaaa");
        }

        dontGarbageMe.put("map", null);

        System.out.println("After=" + getFreeMemInMB() + " MB");
    }

    private long getFreeMemInMB() {
        return Runtime.getRuntime().freeMemory() / (1024 * 1024);
    }

    public static void main(String[] args) {
        Memory m = new Memory();
        m.useMemInMB(15);  // put here apropriate huge value
    }
}
0
votes

It does seem that most of the answers are not C style memory leaks.

I thought I'd add an example of a library class with a bug that will give you an out-of-memory exception. Again, it is not a true memory leak, but it is an example of something running out of memory that you would not expect.

public class Scratch {
    public static void main(String[] args) throws Exception {
        long lastOut = System.currentTimeMillis();
        File file = new File("deleteme.txt");

        ObjectOutputStream out;
        try {
            out = new ObjectOutputStream(
                    new FileOutputStream("deleteme.txt"));

            while (true) {
                out.writeUnshared(new LittleObject());
                if ((System.currentTimeMillis() - lastOut) > 2000) {
                    lastOut = System.currentTimeMillis();
                    System.out.println("Size " + file.length());
                    // out.reset();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class LittleObject implements Serializable {
    int x = 0;
}

You will find the original code and bug description at JDK-4363937: ObjectOutputStream is creating a memory leak