package org.jboss.cache.lock;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Map which reduces concurrency and potential memory leaks for non-static ThreadLocals.
 * http://www.me.umn.edu/~shivane/blogs/cafefeed/2004/06/of-non-static-threadlocals-and-memory.html
 *
 * @author Brian Dueck
 * @version $Id: ThreadLocalMap.java 5665 2008-04-24 14:45:57Z manik.surtani@jboss.com $
 */
public class ThreadLocalMap<K, V> implements Map<K, V>
{

   private final ThreadLocal threadLocal = new ThreadLocal()
   {
      @Override
      protected Object initialValue()
      {
         return new HashMap();
      }
   };

   @SuppressWarnings("unchecked")
   private Map<K, V> getThreadLocalMap()
   {
      return (Map<K, V>) threadLocal.get();
   }

   public V put(K key, V value)
   {
      return getThreadLocalMap().put(key, value);
   }

   public V get(Object key)
   {
      return getThreadLocalMap().get(key);
   }

   public V remove(Object key)
   {
      return getThreadLocalMap().remove(key);
   }

   public int size()
   {
      return getThreadLocalMap().size();
   }

   public void clear()
   {
      getThreadLocalMap().clear();
   }

   public boolean isEmpty()
   {
      return getThreadLocalMap().isEmpty();
   }

   public boolean containsKey(Object arg0)
   {
      return getThreadLocalMap().containsKey(arg0);
   }

   public boolean containsValue(Object arg0)
   {
      return getThreadLocalMap().containsValue(arg0);
   }

   public Collection<V> values()
   {
      return getThreadLocalMap().values();
   }

   public void putAll(Map<? extends K, ? extends V> arg0)
   {
      getThreadLocalMap().putAll(arg0);
   }

   public Set<Map.Entry<K, V>> entrySet()
   {
      return getThreadLocalMap().entrySet();
   }

   public Set<K> keySet()
   {
      return getThreadLocalMap().keySet();
   }

}