Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak caused by Logger

I read that the following code leads to a memory leak as the Level class holds a reference to the CUSTOMLEVEL member from outside the Classloader:

public class LeakServlet extends HttpServlet {
  private static final String STATICNAME = "This leaks!";
  private static final Level CUSTOMLEVEL = new Level("test", 550) {}; // anon class!

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
                 throws ServletException, IOException {
      Logger.getLogger("test").log(CUSTOMLEVEL, "doGet called");
  }
}

The question is how is the Level class loaded outside this particular classloader ?
Can I have some other instances within the java API of a similar behaviour?

like image 817
IUnknown Avatar asked May 27 '13 08:05

IUnknown


People also ask

Can logging cause memory leak?

console. log() causes memory leaks but only when the console is opened. Normally users do not open the console. So it is totally safe to print any huge objects to the console.

What is the main cause of memory leaks?

A memory leak starts when a program requests a chunk of memory from the operating system for itself and its data. As a program operates, it sometimes needs more memory and makes an additional request.

Which action causes memory leak?

In general, a Java memory leak happens when an application unintentionally (due to logical errors in code) holds on to object references that are no longer required. These unintentional object references prevent the built-in Java garbage collection mechanism from freeing up the memory consumed by these objects.


1 Answers

There are lots of sources for class loader leaks: This part of a blog series on the issue, enumerates some of the culprits.

like image 163
forty-two Avatar answered Sep 19 '22 01:09

forty-two