Issue
According to official doc, LocaleContextHolder is:
Simple holder class that associates a LocaleContext instance with the current thread.
So it is tied to current thread
, but is this talking about the Thread
thread or a thread of current request.
Apologize if it is a dumb question, I am not sure a LocaleContextHolder is tied to a HTTP session or something so that it is safe to use in any service layer class.
Solution
If you look at the source code for LocaleContextHolder
, you will notice it has a ThreadLocal
variable (it has two actually)
private static final ThreadLocal<LocaleContext> localeContextHolder =
new NamedThreadLocal<LocaleContext>("Locale context");
You can read about what a ThreadLocal
is but for our sake, consider it a data structure that maps the ID of the current executing thread to an object of its generic type, LocaleContext
here.
A Servlet container has a pool of threads it uses to handle client requests. When a request comes in, it will extract one of these threads and execute your servlet's service()
method. With Spring, this results in DispatcherServlet
executing and your @Controller
's handler method being called. This all happens in that original Thread
the servlet container chose.
So when your @Service
class' method gets called, you're still in that same thread.
The ThreadLocal
in LocaleContextHolder
is set()
at some point early on in request processing, in FrameworkServlet
(which is the parent type of DispatcherServlet
) method initContextHolders()
called by processRequest()
in each of doGet()
, doPost()
, etc. methods. The Locale
is built from the HttpServletRequest
with its getLocale()
method.
Answered By - Sotirios Delimanolis
Answer Checked By - Robin (JavaFixing Admin)