ITeye博客

ThreadLocal在spring中的使用

dmwdmc · 2013-06-05 10:16 · 线程 · 编程语言 · Markdown

spring mvc中它的核心类是DispatcherServlet,

在处理请求时,我们看到它如果掉用了doService方法里的doDispath方法。

 protected void doService(HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
 ......
      doDispatch(request, response);


......
     }

doDispatch 方法中,会去拿RequestContextHolder.getRequestAttributes();

而RequestContextHolder.getRequestAttributes() 方法的实现就是从ThreadLocal中取:

public abstract class RequestContextHolder
{
 private static final ThreadLocal requestAttributesHolder = new ThreadLocal();

  private static final ThreadLocal inheritableRequestAttributesHolder = new InheritableThreadLocal();
  public static RequestAttributes getRequestAttributes()
  {
    RequestAttributes attributes = (RequestAttributes)requestAttributesHolder.get();
    if (attributes == null) {
      attributes = (RequestAttributes)inheritableRequestAttributesHolder.get();
    }
    return attributes;
  }

}

从而保证的request 里面value的线程安全。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。