Fundamentals 6 min read

How to Write Java Code That Causes a Memory Leak

Various techniques for deliberately creating memory leaks in Java are presented, including using long‑running threads with custom class loaders, static references, ThreadLocal misuse, improper handling of resources like connections and streams, and flawed implementations of hashCode/equals, each illustrated with code examples.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
How to Write Java Code That Causes a Memory Leak

Question: How to write Java code that will cause a memory leak?

A1: Describes a pattern where a long‑running thread (or thread pool) loads a class with a custom class loader, allocates large memory (e.g., new byte[1000000]) stored in a static field and also in a ThreadLocal, then cleans up the class loader while the ThreadLocal still holds a reference, preventing garbage collection. Repeating this leads to accumulation of unreclaimed memory, especially in permgen/Metaspace.

A2: Lists simple leak sources such as static variable holding objects, using String.intern() on large strings, and failing to close JDBC connections. Example snippets:

class MemorableClass {
    static final ArrayList list = new ArrayList(100);
}
String str = readString(); // read lengthy string any source db,textbox/jsp etc..
str.intern(); // places the string in the JVM string pool
try {
    Connection conn = ConnectionFactory.getConnection();
    // ... use connection ...
} catch (Exception e) {
    e.printStackTrace();
}

A3: Shows that a HashSet or Map with objects that do not correctly implement hashCode() and equals() can cause continuous growth because duplicate entries cannot be eliminated. Example:

class BadKey {
    // no hashCode or equals();
    public final String key;
    public BadKey(String key) { this.key = key; }
}
Map map = System.getProperties();
map.put(new BadKey("key"), "value"); // Memory leak even if your threads die.

A4: Describes less obvious thread‑related leaks: shutdown hooks not removed, threads created but never started, threads that retain ContextClassLoader or AccessControlContext, misuse of ThreadLocal caches, ThreadGroup destruction, WeakHashMap value referencing key, URL KeepAliveCache, and native resources from Inflater/Deflater not being closed, all of which can keep classes, class loaders, or native memory from being reclaimed.

Source: CoolSkill article (http://www.coolskill.net/article/java-coding-oom.htm).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javamemory leakThreadLocalStatic Reference
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.