Home » Java » java – How to keep context when creating new thread in spring?-Exceptionshub

java – How to keep context when creating new thread in spring?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:
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?

How to&Answers:

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.