How to Engineer a Memory Leak in Java
When asked to demonstrate memory leaks during an interview, it's understandable to feel puzzled. Here's how to craft a true memory leak with pure Java:
This approach exploits a limitation in ThreadLocal implementation. While each key in the threadLocals map is a weak reference that allows associated ThreadLocal objects to be garbage collected, the corresponding value holds a strong reference. If the value references the ThreadLocal object, a circular dependency is formed, preventing both entities from being garbage collected.
Ultimately, this creates a leak with strong references:
ClassLoader also contributes to the leak by adding an extra reference chain:
This pattern has led to severe memory leaks in application containers like Tomcat, where frequently redeploying applications using ThreadLocals creates hidden references.
The above is the detailed content of How Can I Deliberately Create a Memory Leak in Java?. For more information, please follow other related articles on the PHP Chinese website!