利用ThreadLocal实现全局上下文工具类

来源:互联网 发布:linux如何安装vnc 编辑:程序博客网 时间:2024/06/05 19:47
/** * 全局上下文工具类,用于储存一些东西 */public class MyContext {    private static final ThreadLocal<Map<Object, Object>> mycontext = new ThreadLocal<Map<Object, Object>>() {        @Override        protected Map<Object, Object> initialValue() {            return new HashMap<Object, Object>();        }    };    /**     * 根据key获取值     * @param key     * @return     */    public static Object getValue(Object key) {        if(mycontext.get() == null) {            return null;        }        return mycontext.get().get(key);    }    /**     * 存储     * @param key     * @param value     * @return     */    public static Object setValue(Object key, Object value) {        Map<Object, Object> cacheMap = mycontext.get();        if(cacheMap == null) {            cacheMap = new HashMap<Object, Object>();            mycontext.set(cacheMap);        }        return cacheMap.put(key, value);    }    /**     * 根据key移除值     * @param key     */    public static void removeValue(Object key) {        Map<Object, Object> cacheMap = mycontext.get();        if(cacheMap != null) {            cacheMap.remove(key);        }    }    /**     * 重置     */    public static void reset() {        if(mycontext.get() != null) {            mycontext.get().clear();        }    }}

0 0
原创粉丝点击