对ThreadLocal的高级封装
- 显示的声明Scope的范围
- 强类型
- 可以在线程池中安全的使用,并防止泄露
- 只支持jdk1.8
privatestaticfinalScopeKey<String> TEST_KEY = allocate(); publicvoidbasicUse(){runWithNewScope(() ->{TEST_KEY.set("abc"); Stringresult = TEST_KEY.get(); // get "abc"runAsyncWithCurrentScope(()->{StringresultInScope = TEST_KEY.get(); // get "abc" }, executor)})} // 或者声明一个Scope友好的ExecutorService,方法如下:privatestaticclassScopeThreadPoolExecutorextendsThreadPoolExecutor{ScopeThreadPoolExecutor(intcorePoolSize, intmaximumPoolSize, longkeepAliveTime, TimeUnitunit, BlockingQueue<Runnable> workQueue){super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue)} /** * same as{@link java.util.concurrent.Executors#newFixedThreadPool(int)} */staticScopeThreadPoolExecutornewFixedThreadPool(intnThreads){returnnewScopeThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, newLinkedBlockingQueue<Runnable>())} /** * 只要override这一个方法就可以 * 所有submit, invokeAll等方法都会代理到这里来 */@Overridepublicvoidexecute(Runnablecommand){Scopescope = getCurrentScope(); super.execute(() -> runWithExistScope(scope, command::run))} } privateExecutorServiceexecutor = ScopeThreadPoolExecutor.newFixedThreadPool(10); publicvoidexecuteTest(){runWithNewScope(() ->{TEST_KEY.set("abc"); executor.submit(() ->{TEST_KEY.get(); // get abc })})}