InheritableThreadLocal and thread pools

后端 未结 2 1870
无人共我
无人共我 2020-12-16 18:43

I have a problem which I don\'t really think has a solution but I\'ll try here anyway. My application uses a thread pool and some of the threads in this pool have an inherit

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 18:58

    The constructor of a runnable runs in the thread of the caller, whereas the run method runs in the child thread. You can use this fact to transfer information from the parent to the child thread. See:

    public class ThreadlocalApplication {
    static public ThreadLocal tenantId = new ThreadLocal<>();
    
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executor = Executors.newCachedThreadPool();
        System.out.println(Thread.currentThread().getName());
        ThreadlocalApplication.tenantId.set("4711");
        executor.submit(new AsyncTask()).get();
        executor.shutdown();
    }
    
    static class AsyncTask implements Runnable {
        private String _tenantId;
    
        public AsyncTask() {
            System.out.println(Thread.currentThread().getName());
            _tenantId = ThreadlocalApplication.tenantId.get();
        }
    
        @Override
        public void run() {
            ThreadlocalApplication.tenantId.set(_tenantId);
            System.out.println(Thread.currentThread().getName());
            System.out.println(ThreadlocalApplication.tenantId.get());
        }
    }
    }
    

    And this is the result

    main
    main
    pool-1-thread-1
    4711
    

提交回复
热议问题