ThreadLocalMap 减少实例化ThreadLocal 对象

java代码实现:

package com.test.ThreadLocalMap ;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;



public class ThreadLocalMap {

    private static Logger logger = LoggerFactory.getLogger(ThreadLocalMap.class);

    protected final static ThreadLocal> threadContext = new MapThreadLocal();

    private ThreadLocalMap(){};

    public static void put(String key,Object value){
        getContextMap().put(key,value);
    }

    public static Object remove(String key){
        return getContextMap().remove(key);
    }

    public static Object get(String key){
        return getContextMap().get(key);
    }

    private static class MapThreadLocal extends ThreadLocal> {
        protected Map initialValue() {
            return new HashMap() {

                private static final long serialVersionUID = 3637958959138295593L;

                public Object put(String key, Object value) {
                    if (logger.isDebugEnabled()) {
                        if (containsKey(key)) {
                            logger.debug("Overwritten attribute to thread context: " + key
                                    + " = " + value);
                        } else {
                            logger.debug("Added attribute to thread context: " + key + " = "
                                    + value);
                        }
                    }

                    return super.put(key, value);
                }
            };
        }
    }

    /**
     * 取得thread context Map的实例。
     *
     * @return thread context Map的实例
     */
    protected static Map getContextMap() {
        return  threadContext.get();
    }


    /**
     * 清理线程所有被hold住的对象。以便重用!
     */

    public static void reset(){
        getContextMap().clear();
    }
}

 

你可能感兴趣的:(java)