简体   繁体   中英

Is LocaleContextHolder safe in service layer

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 a LocaleContextHolder is not tied to a HTTP session or something so that it is safe to use in any service layer class.

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.

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