一个好用的 ThreadLocal 工具类

开篇

  又是好久没有写博客了,今天就放一段代码吧

背景

   工作需要,写了一个 ThreadLocal 工具类,供大家使用,并欢迎大家提出改进意见 (~ _ ~),共勉!
   更复杂的功能并没有开发,有需求再迭代就可,代码一定要保持kiss原则,简既是美.

/**
 * ThreadLocal 工具类
 *
 * @author :Lingyun
 * @date :2020-07-01 16:53
 */
public class ThreadLocalUtil {

    private static final ThreadLocal> threadLocal = ThreadLocal.withInitial(() -> new HashMap<>(10));

    public static Map getThreadLocal() {
        return threadLocal.get();
    }

    public static  T get(String key) {
        Map map = threadLocal.get();
        return get(key, null);
    }

    @SuppressWarnings("unchecked")
    public static  T get(String key, T defaultValue) {
        Map map = threadLocal.get();
        return (T) Optional.ofNullable(map.get(key)).orElse(defaultValue);
    }

    public static void set(String key, Object value) {
        Map map = threadLocal.get();
        map.put(key, value);
    }

    public static void set(Map keyValueMap) {
        Map map = threadLocal.get();
        map.putAll(keyValueMap);
    }

    public static void remove() {
        threadLocal.remove();
    }

    @SuppressWarnings("unchecked")
    public static  T remove(String key) {
        Map map = threadLocal.get();
        return (T) map.remove(key);
    }

}

你可能感兴趣的:(一个好用的 ThreadLocal 工具类)