package com.utils; /** * ThreadLocalUtil * +---------------------------------------------------------------------- * | CRMEB [ CRMEB赋能开发者,助力企业发展 ] * +---------------------------------------------------------------------- * | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved. * +---------------------------------------------------------------------- * | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权 * +---------------------------------------------------------------------- * | Author: CRMEB Team * +---------------------------------------------------------------------- */ import java.util.*; public final class ThreadLocalUtil { private ThreadLocalUtil() { throw new IllegalStateException("Utility class"); } private static final ThreadLocal> threadLocal = ThreadLocal.withInitial(() -> new HashMap(4)); public static Map getThreadLocal(){ return threadLocal.get(); } public static T get(String key) { Map map = (Map)threadLocal.get(); return (T)map.get(key); } public static T get(String key,T defaultValue) { Map map = (Map)threadLocal.get(); return (T)map.get(key) == null ? defaultValue : (T)map.get(key); } public static void set(String key, Object value) { Map map = (Map)threadLocal.get(); map.put(key, value); } public static void set(Map keyValueMap) { Map map = (Map)threadLocal.get(); map.putAll(keyValueMap); } public static void remove() { threadLocal.remove(); } public static Map fetchVarsByPrefix(String prefix) { Map vars = new HashMap<>(); if( prefix == null ){ return vars; } Map map = (Map)threadLocal.get(); Set set = map.entrySet(); for( Map.Entry entry : set ){ Object key = entry.getKey(); if( key instanceof String ){ if( ((String) key).startsWith(prefix) ){ vars.put((String)key,(T)entry.getValue()); } } } return vars; } public static T remove(String key) { Map map = (Map)threadLocal.get(); return (T)map.remove(key); } public static void clear(String prefix) { if( prefix == null ){ return; } Map map = (Map)threadLocal.get(); Set set = map.entrySet(); List removeKeys = new ArrayList<>(); for( Map.Entry entry : set ){ Object key = entry.getKey(); if( key instanceof String ){ if( ((String) key).startsWith(prefix) ){ removeKeys.add((String)key); } } } for( String key : removeKeys ){ map.remove(key); } } }