6

I have a thread and it contains ThreadLocal variable. I need to use parallelStream() inside the above mentioned thread. Need to call myService which uses the thread local variable. Is there any mechanism to set the ThreadLocal when using parallelstream() in java8.

List<MyObject> result = myList.parallelStream().map(myObject -> {
    //call myService with the Threadlocal 
}).filter(...)
.....;
Didier L
  • 18,905
  • 10
  • 61
  • 103
Akila
  • 187
  • 2
  • 9
  • please check this [link](https://stackoverflow.com/questions/33926777/java-8-parallel-stream-and-threadlocal), hope it answers your question. – Amir Jan 29 '18 at 06:27
  • 2
    Please check this [link](https://stackoverflow.com/questions/33926777/java-8-parallel-stream-and-threadlocal) for your question, hope it helps. – Amir Jan 29 '18 at 06:29
  • 1
    If myService is relying on a thread local variable, it’s very likely not ready to get invoked by multiple threads anyway. – Holger Jan 29 '18 at 14:47

1 Answers1

0

you can easily set threadLocal variable before you call the service. within the map, you can set the value from main threadlocal value or any other value.

 ThreadLocal<String> threadLocal= new ThreadLocal<>();

        IntStream.range(0, 8).parallel().forEach(n -> {
            threadLocal.set("MAIN");
            System.out.println("This is sequence access "+n);
            System.out.printf("Service used ThreadLocal - %d: %s\n", n, threadLocal.get());
        });

Outcome:

This is sequence access 5
This is sequence access 7
Parallel Consumer - 5: MAIN
Parallel Consumer - 7: MAIN
This is sequence access 4
This is sequence access 6
Parallel Consumer - 4: MAIN
Parallel Consumer - 6: MAIN
This is sequence access 2
This is sequence access 1
Parallel Consumer - 2: MAIN
This is sequence access 0
This is sequence access 3
Parallel Consumer - 0: MAIN
Parallel Consumer - 1: MAIN
Parallel Consumer - 3: MAIN
  • 6
    This is not a useful answer. That technique works in this trivial example, where all the code is in the same place; but in that case, why would anyone use a ThreadLocal? In a real system, you're using a ThreadLocal to set some context at the bottom of the call stack, so you don't have to pass that context as an argument from method to method to method until it finally gets to the place where the parallel stream executes. Some of those intervening methods might be in code that you don't even control and can't modify. – Doradus Aug 23 '19 at 12:27