I just had an interview where I was asked to create a memory leak with Java.
Needless to say, I felt pretty dumb, having no idea how to start creating one.
What would an example be?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here’s a good way to create a true memory leak (objects inaccessible by running code but still stored in memory) in pure Java:
ClassLoader.new byte[1000000]), stores a strong reference to it in a static field, and then stores a reference to itself in aThreadLocal. Allocating the extra memory is optional (leaking the class instance is enough), but it will make the leak work that much faster.ClassLoaderit was loaded from.Due to the way
ThreadLocalis implemented in Oracle’s JDK, this creates a memory leak:Threadhas a private fieldthreadLocals, which actually stores the thread-local values.ThreadLocalobject, so after thatThreadLocalobject is garbage-collected, its entry is removed from the map.ThreadLocalobject that is its key, that object will neither be garbage-collected nor removed from the map as long as the thread lives.In this example, the chain of strong references looks like this:
Threadobject →threadLocalsmap → instance of example class → example class → staticThreadLocalfield →ThreadLocalobject.(The
ClassLoaderdoesn’t really play a role in creating the leak, it just makes the leak worse because of this additional reference chain: example class →ClassLoader→ all the classes it has loaded. It was even worse in many JVM implementations, especially prior to Java 7, because classes andClassLoaders were allocated straight into permgen and were never garbage-collected at all.)A variation on this pattern is why application containers (like Tomcat) can leak memory like a sieve if you frequently redeploy applications which happen to use
ThreadLocals that in some way point back to themselves. This can happen for a number of subtle reasons and is often hard to debug and/or fix.Update: Since lots of people keep asking for it, here’s some example code that shows this behavior in action.