title: Strategy in java to clean up / remove unused map elements
body: <p>I'm implementing a "manager" in my web app that can be called to set and get  which web site context the current thread is in (we white label our site so the web site context represents which site we're on)</p>
  
  <p>I'm trying to work out what the best strategy to do this,  currently I'm implementing the store of Threads to WebSiteContexts in a concurrent hash map:</p>
  
  <pre><code>private final ConcurrentHashMap&lt;Thread, WebSiteContext&gt; chm = new ConcurrentHashMap&lt;Thread, WebSiteContext&gt;();
  </code></pre>
  
  <p>at the beginning of the thread (either through a Servlet Filter or through manually setting it) the thread will be associated to its WebSiteContext,</p>
  
  <p>but want to clean up the Map to avoid a memory leak.   So I guess one strategy is to iterate through the Thread keys of the map to find out whether the threads are "alive" (thread.isAlive())  and if not remove it for example like this: </p>
  
  <pre><code> public class Cleaner implements Runnable {
        private static final int INTERVAL = 6 * 1000; // 6 seconds
        public Cleaner() {
        }
        public void run() {
              // soo every interval iterate through the threads if they're dead then remove it from the map.
              while(true) {
                 try {
                       Set&lt;Thread&gt; threads = chm.keySet();
                       Set&lt;Thread&gt; staleThreads = new HashSet&lt;Thread&gt;();
                       for (Thread tmpThread : threads) {
  
                          // if we get to a dead thread then clean the fucker up
                          if (!tmpThread.isAlive()) {
                             // think that we're going to get a run condition anyway
                             chm.remove(tmpThread);
                          }
                       }
                    Thread.sleep(INTERVAL);
                 } catch (Exception e) {
                    log.error("caught exception e:", e);
                 }
              }
        }
     }
  </code></pre>
  
  <p>, but this I guess requires me to synchronize  access to the map (or does it?) which is something I want to avoid.</p>
  
  <p>Is there any "idiomatic" pattern for storing attributes in threads in java or indeed cleaning up maps that have Thread objects as keys?  I'm open to using WeakReference / SoftReferences or indeed if there is some equivalent of Thread.getCurrentThread().setAttribute(Object, Object),  that would be great</p>
  
  <p>Cheers
  Simon B</p>