How to leak memory in java

Create some ghost memory

  1. Create a long exist thread or thread pool.
  2. Load a class through ClassLoader.
  3. Distribute a big block memory to a static strong reference.
    Then use ThreadLocal storage [thread reference?] or [object reference?]
  4. Thread clean selfdefine class or load this class’s loader.
  5. repeat these steps.

Some mistake

  1. static reference hold container.

    1
    2
    3
    class Holder {
    static final List list = new ArrayList(100);
    }
  2. call long String’s intern() method

    1
    2
    String src = "......";
    str.intern();
  3. forgot release resource

    1
    2
    3
    4
    5
    6
    7
    try {
    BufferedReader br = new BufferedReader(new FileReader("..."));
    ...
    ...
    } catch (Exception e) {
    e.printStacktrace();
    }
  4. forgot close door

    1
    2
    3
    4
    5
    6
    7
    try {
    Connection conn = ConnectionFactory.getConnection();
    ...
    ...
    } catch (Exception e) {
    e.printStacktrace();
    }
  5. GC can’t reach like native true memory

  6. Web container in application context
    getServletContext().setAttribute("rubbish", map);
    no reboot and not remove rubbish.

  7. Web container in session context
    session.setAttribute("rubbish", map);
    no reboot / not invalid and not remove rubbish.

  8. Not right JVM option
    IBM JDK noclassgc option, it stop no use class’s garbage collect.

Bean not define properly

If HashSet’s element object have no standard implement
or no implement of equals() and hashCode().
Collection can’t ignore repeated element.

Thread relevant

  1. Create but not start thread.
  2. Thread inherited ContextClassLoader or ccessControlContext,
    and use ThreadGroup or InheritedThreadLocal.
    They affect java.util.concurrent.Executor

  3. Not use ThreadLocal as cache unless truly necessary.
    If thread not in it’s life cycle, load ContextClassLoader, gc can’t reach it.

  4. When ThreadGroup have no subThread
    but have sub ThreadGroup call ThreadGroup.destroy().
    It lead to this sub ThreadGroup can’t remove from it’s parent ThreadGroup.

  5. use WeakHashMap, value hold key reference..