Java 8 parallel stream and ThreadLocal

前端 未结 1 856
长发绾君心
长发绾君心 2021-02-01 09:01

I am trying to figure out how can I copy a ThreadLocal value in Java 8 parallel stream.

So if we consider this:

    public class ThreadLocalTest {

              


        
1条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-01 09:35

    As Louis has stated in the comments, your example can very well be reduced to capturing the value of a local variable in the lambda expression

    public static void main(String[] args)  {
        String value = "MAIN";
        System.out.printf("Main Thread: %s\n", value);
    
        IntStream.range(0,8).boxed().parallel().forEach(n -> {
            System.out.printf("Parallel Consumer - %d: %s\n", n, value);
        });
    }
    

    It's not obvious from your example what the full use case is.

    If you know exactly which threads will be started from your main thread, you may consider using an InheritableThreadLocal

    This class extends ThreadLocal to provide inheritance of values from parent thread to child thread: when a child thread is created, the child receives initial values for all inheritable thread-local variables for which the parent has values.

    In your case, declaring val as an InheritableThreadLocal, since the Thread instances created for parallel() within the ForkJoinPool#commonPool() are created lazily, they would all inherit from the value set in the main method (and thread).

    This wouldn't be the case if you somehow used the commonPool (or whatever pool the parallel terminal operation was called on) before you set the InhertiableThreadLocal value in the origin thread.

    0 讨论(0)
提交回复
热议问题