title: How to integrate memcached in a Servlet? Tomcat & memory leaks
body: <p>Searching memcached java in google, the first result is <a href="http://sacharya.com/using-memcached-with-java/" rel="nofollow">Using Memcached with Java</a>.</p>
  
  <p>The guy (who calls himself <em>Just some Random Asshole in the Internet!</em>) proposes a Singleton based on <strong>net.spy.memcached</strong>. It basically creates 20 threads and connections by creating 20 instances of MemcachedClient. For every request it chooses one at random.</p>
  
  <p>However those threads and connections are never closed and they pile up every time I hot swap the application during development (with warnings from Tomcat 7).</p>
  
  <pre><code>SEVERE: The web application [/MyAppName] appears to have started a thread named
  [...] but has failed to stop it. This is very likely to create a memory leak.
  </code></pre>
  
  <p>By looking at MemcachedClient JavaDoc, I see a method called <strong>shutdown</strong> with the only description being "Shut down immediately." Shut down what? The client? The server? I suppose is the client, since it's in MemcachedClient and I suppose that this method would close the connection and terminate the thread. <strong>EDIT</strong>: yes, it shuts down the client.</p>
  
  <p><strong>Question 1</strong> How to force the execution of cleanup code in Tomcat 7, before the application is hot swapped?</p>
  
  <p><strong>Question 2</strong> Is this approach of using memcached (with cleanup code), correct or is better I start over in a different way?</p>