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(...)
.....;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With