ThreadLocal底层是个map每次set值的时候把当前线程与值放到里面ThreadLocal.ThreadLocalMap threadLocals = null;
这种结构在大数据量并发请求时会,会产生内存泄漏。 请求时set进去,正常退出move掉,来不及remove的数据会停留在内存中,外界还有引用,gc不会收就会泄露
如果子线程需要使用父级的数据去处理任务,然后回到父线程归纳处理,这时候ThreadLocal就不满足了
private static ThreadLocal<String> inheritableThreadLocal = new ThreadLocal<>();public static void main(String[] args) throws IOException {inheritableThreadLocal.set("Value from parent thread");// 创建线程池ExecutorService executorService = Executors.newFixedThreadPool(5);// 提交任务(创建子线程)for (int i = 0; i < 5; i++) {executorService.submit(() -> {try {// 子线程中获取从父线程继承的值String value = (String) inheritableThreadLocal.get();System.out.println("Value in child thread: " + value);} finally {// 任务执行完毕后清除值inheritableThreadLocal.remove();}});}// 关闭线程池executorService.shutdown();}
这时候子线程获取父级线程的数据就是空
InheritableThreadLocal是ThreadLocal子类,其区别