2

I have a service which has methods sending emails asyncronously. Sender method has an @Async annotation. But when I try to use current locale in that method, It always the default one. So question is how to pass locale to @Async methods.

6
  • 3
    Just pass it into the method.
    – M. Deinum
    Commented Nov 17, 2016 at 13:03
  • can you share your example code?
    – pleft
    Commented Nov 17, 2016 at 13:04
  • @M.Deinum Is there more general and elegant solution than to pass Locale in every method?
    – iamorozov
    Commented Nov 17, 2016 at 13:11
  • @pleft Sorry, there is a kind of complex logic around
    – iamorozov
    Commented Nov 17, 2016 at 13:12
  • 2
    Not really... It runs in a different thread, so using LocaleContextHolder isn't an option as that is based on a ThreadLocal (that is also why you are getting the default Locale instead of the one you expect).
    – M. Deinum
    Commented Nov 17, 2016 at 13:16

3 Answers 3

3

The solution of chunhoong worked for me, but It's not so semantic. There was a better solution for me: Set the same request context for all threads. The main and all the @Async threads should share the DispatcherServlet context (setThreadContextInheritable(true)). It worked like a charm:

@SpringBootApplication
public class CoreApplication {
    public static void main(String[] args) {
        SpringApplication
                .run(CoreApplication.class, args)
                .getBean(DispatcherServlet.class)
                .setThreadContextInheritable(true);
    }
}

PS: This helped me a lot: https://github.com/spring-projects/spring-boot/issues/14079

2

I believe you are accessing your current locale using LocaleContextHolder.

Before execute your async method, set your current locale into LocaleContextHolder with inheritable flag set to true, eg:

Locale currentLocale = LocaleContextHolder.getLocale();
LocaleContextHolder.setLocale(currentLocale, true);

The LocaleContext will be inherited by any child threads spawned by the current thread when the inheritable flag is set to true, which behaves like a thread-local.

Reference: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/i18n/LocaleContextHolder.html#setLocale-java.util.Locale-boolean-

0

It is possible to implement custom AsyncTaskExecutor which would take a Locale as a parameter. Then it would set a locale to its context.

public interface LocaleAsyncTaskExecutor extends AsyncTaskExecutor {
    void execute(Runnable task, Locale locale);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.