How to set ThreadLocal for parallelStream

I have a thread and it contains a Threadlocal variable. I need to use parallelStream inside the above stream. You must call myServicethat uses the local stream variable. Is there any mechanism for installing ThreadLocal when using parallel thread in java8.

    List<MyObject> result = myList.parallelStream().map(myObject -> {
        //call myService with the Threadlocal 
    }).filter(...)
    .....;
+4
source share
1 answer

you can easily set the threadLocal variable before calling the service. within the map, you can set the value from the 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());
        });

Result:

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
+2
source

Source: https://habr.com/ru/post/1692857/


All Articles