3
System.out.println(LocaleContextHolder.getLocale()); // zh
new Thread(() -> {
    System.out.println(LocaleContextHolder.getLocale()); // en_US
}).start();

From parent thread, I see that context locale is "zh" from child thread, I see "en_US". New thread is losing the context locale. Is there a way to pass context to new created thread?

2 Answers2

2

According to the Javadocs

The LocaleContext will be inherited by any child threads spawned by the current thread if the inheritable flag is set to true.

This means locale can be set using the method setLocale(Locale locale, boolean inheritable) by passing inheritable as true. So before spawning a new child thread you can call setLocale with inheritable equals to true.

Tarun Gupta
  • 1,629
  • 1
  • 22
  • 39
0

use transmittable-thread-local,add dependence to your pom.xml

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>transmittable-thread-local</artifactId>
  <version>2.12.0</version>
</dependency>

convert you executorService like this

ExecutorService executorService = ...
executorService = TtlExecutors.getTtlExecutorService(executorService);
袁文涛
  • 735
  • 1
  • 10
  • 23