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.
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).
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
