Using InheritableThreadLocal with ThreadPoolExecutor — or — a ThreadPoolExecutor that doesn't reuse threads

前端 未结 4 1988
盖世英雄少女心
盖世英雄少女心 2020-12-10 01:58

I am trying to use both InheritableThreadLocal and a ThreadPoolExecutor.

This breaks down because ThreadPoolExecutor reuses th

4条回答
  •  感情败类
    2020-12-10 02:36

    using InheritedThreadLocal is almost surely wrong. Probably you'd have not asked the question if you can fit that bizarre tool. First and foremost it's horribly leak-prone and often the value(s) escapes in some totally strange threads.

    As for the Runnable being associate w/ a context. Override publicvoid execute(Runnable command) of the ExecutorPool and wrap the Runnable withing some context carrying the value you want in the first place from the InheritedThreadLocal.

    The wrapping class shall look something like

    class WrappedRunnable extends Runnable{
      static final ThreadLocal context=new ThreadLocal();
      final Runnable target;
      final Ctx context;
      WrappedRunnable(Ctx context, Runnable target){...}
    
      public void run(){
        ctx.set(context);
        try{ 
          target.run();
        }finally{
          ctx.set(null);//or ctx.remove()
        }
      }
    }
    

    Alternatively, is there any implementation of ThreadPoolExecutor that creates a new >thread each time it starts a new Runnable? For my purposes I only care about gating the >number of simultaneously running threads to a fixed size.

    While truly bad from performance point of view, you can implement your own, basically you need only execute(Runnable task) method for the Executor that spawns new thread and starts it.

提交回复
热议问题