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

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.

Answered By – Tarun Gupta

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published