How can I create a memory leak in Java?

后端 未结 30 1731
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 22:26

I just had an interview, and I was asked to create a memory leak with Java.

Needless to say, I felt pretty dumb having no clue on how to eve

30条回答
  •  -上瘾入骨i
    2020-11-21 22:47

    I recently encountered a memory leak situation caused in a way by log4j.

    Log4j has this mechanism called Nested Diagnostic Context(NDC) which is an instrument to distinguish interleaved log output from different sources. The granularity at which NDC works is threads, so it distinguishes log outputs from different threads separately.

    In order to store thread specific tags, log4j's NDC class uses a Hashtable which is keyed by the Thread object itself (as opposed to say the thread id), and thus till the NDC tag stays in memory all the objects that hang off of the thread object also stay in memory. In our web application we use NDC to tag logoutputs with a request id to distinguish logs from a single request separately. The container that associates the NDC tag with a thread, also removes it while returning the response from a request. The problem occurred when during the course of processing a request, a child thread was spawned, something like the following code:

    pubclic class RequestProcessor {
        private static final Logger logger = Logger.getLogger(RequestProcessor.class);
        public void doSomething()  {
            ....
            final List hugeList = new ArrayList(10000);
            new Thread() {
               public void run() {
                   logger.info("Child thread spawned")
                   for(String s:hugeList) {
                       ....
                   }
               }
            }.start();
        }
    }    
    

    So an NDC context was associated with inline thread that was spawned. The thread object that was the key for this NDC context, is the inline thread which has the hugeList object hanging off of it. Hence even after the thread finished doing what it was doing, the reference to the hugeList was kept alive by the NDC context Hastable, thus causing a memory leak.

提交回复
热议问题