ThreadLocal在spring中的使用

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的线程安全。

你可能感兴趣的:(线程)