简体   繁体   中英

How to keep context when creating new thread in spring?

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?

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 .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM