title: When to remove from the MDC
body: <p>I recently discovered the magic of using <a href="http://logback.qos.ch/manual/mdc.html" rel="noreferrer">MDCs</a> when logging. It works perfectly.</p>
  
  <p>I have the following method:</p>
  
  <pre><code>public static final String MDC_CLIENT="client";
  public static final String MDC_SESSION="session";
  public static final String MDC_DEVICE="device";
  
  // Called for every request.
  public static void request(final HttpServletRequest request) {
    // The MDC is a thread-local storage accessable from the log formatter.
    MDC.put(MDC_CLIENT, String.format("%s:%s", request.getRemoteHost(), request.getRemotePort()));
    HttpSession session = request.getSession();
    MDC.put(MDC_SESSION, session.getId());
    MDC.put(MDC_DEVICE, (String)session.getAttribute("device"));
    // Also record the context.
    setContext(session.getServletContext());
  }
  </code></pre>
  
  <p>This is called as the first action in every jsp. This allows me to keep track of the details of the session in the log nicely.</p>
  
  <p>However - how do I know when to <code>remove</code> these map entries? What event should I watch for that will allow me to tidy up the map?</p>
  
  <p>I am hosting under Tomcat. If it re-uses threads then I won't leak memory because these are essentially thread-local so each <code>put</code> will overwrite the old <code>put</code> from the last time the thread was used. If it doesn't - or I am hosted under something else that doesn't - I am essentially growing the map potentially forever - or at least until the host is restarted.</p>
  
  <p>I think the essence of my question is - is there an event I can detect that indicates that a particular session or thread is finished with and about to be released.</p>