一个好用的 ThreadLocal 工具类

开篇

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

背景

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

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

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

    public static Map<String, Object> getThreadLocal() {
        return threadLocal.get();
    }

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

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

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

    public static void set(Map<String, Object> keyValueMap) {
        Map<String, Object> map = threadLocal.get();
        map.putAll(keyValueMap);
    }

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

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

}