Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set ThreadLocal for parallelStream

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(...)
.....;
like image 474
Akila Avatar asked Oct 28 '22 19:10

Akila


1 Answers

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
like image 159
Paraneetharan Saravanaperumal Avatar answered Nov 15 '22 10:11

Paraneetharan Saravanaperumal