servlet是單例的,而tomcat則是在多個線程中調用servlet的處理方法。所以若是servlet存在實例對象,那麼就會引出線程安全的問題。而springmvc容許在controller類中經過@Autowired配置request、response以及requestcontext等實例對象。這種配置方法是否線程安全?答案是——這種配置方法是線程安全的,request、response以及requestcontext在使用時不須要進行同步。而根據spring的默認規則,controller對於beanfactory而言是單例的。即controller只有一個,controller中的request等實例對象也只有一個。然而tomcat依舊會以多線程的方式訪問controller。這種作法彷佛並不能保證線程安全。咱們如何理解這一矛盾?web
在解釋controller線程安全這一問題以前須要首先了解以下的一些問題和概念:spring
1.servlet的request域的問題:request域是javaweb的基礎概念,他指的是從發起http請求到返回響應的這一段時間內,存在一個httprequest對象對應於http請求。以上的表述是沒有問題的,然而有些人「自做主張」的將以前的表述換成了其餘的描述方式:(1):request對象的生命週期以發起http請求開始,當http請求返回時結束;(2):用戶發送一個請求的時候,request被建立,當用戶關閉請求的時候,request會消亡。以上兩種表述的主要錯誤在於混淆了http請求和request對象這兩個概念。tomcat在接收到http請求的時候並不會建立一個request對象,即request對象並非一個http請求的實例。只是request對象「恰巧」擁有了http請求中的全部參數而已。request對象在tomcat發起處理線程的時候就被建立,只有當處理線程終止的時候request纔會被銷燬。咱們能夠建立一個servlet類,並在doget和dopost方法上面打上斷點。你會發現若是是同一個進程,即使發起屢次訪問,request對象的id始終不變。讀者能夠親自嘗試,用以驗證本人說法的真僞。tomcat
2.Threadlocal類:該對象包含兩個關鍵函數:set(Object obj)和get()。這兩個函數與調用該函數的線程相關,set方法將某一對象「注入」到當前線程中,而get方法則是從當前線程中獲取對象。安全
3.InvocationHandler接口:這是springmvc保證request對象線程安全的核心。經過實現該接口,開發者可以在Java對象方法執行時進行干預,搭配Threadlocal就可以實現線程安全。多線程
下面將經過例子介紹springmvc如何保證request對象線程安全:mvc
Httprequest接口:框架
- public interface HttpRequest {
- public void service();
- }
HttpRequestImpl類:對httprequest接口的具體實現,爲了區別不一樣的HttpRequestImpl對象,本人爲HttpRequestImpl設置了一個Double對象,若是不設置該對象,其默認爲null
- public class HttpRequestImpl implements HttpRequest{
- public Double d;
- @Override
- public void service() {
- System.out.println("do some serivce, random value is "+d);
- }
-
- }
ThreadLocalTest類:負責向ThreadLocal設置對象和獲取對象,本人設置ThreadLocal對象爲static,所以ThreadLocalTest類中只能有一個ThreadLocal對象。
- public class ThreadLocalTest {
- public static ThreadLocal<HttpRequest> local=new ThreadLocal<HttpRequest>();
- public static void set(HttpRequest f){
- if(get()==null){
- System.out.println("ThreadLocal is null");
- local.set(f);
- }
- }
- public static HttpRequest get(){
- return local.get();
- }
- }
Factory類:該類是一個工廠類而且是單例模式,主要負責向ThreadLocalTest對象中設置和獲取對象
- public class Factory{
- private static Factory factory=new Factory();
- private Factory(){
-
- }
- public static Factory getInstance(){
- return factory;
- }
- public HttpRequest getObject(){
- return (HttpRequest)ThreadLocalTest.get();
- }
- public void setObject(HttpRequest request){
- ThreadLocalTest.set(request);
- }
- }
Delegate類:該類實現了InvocationHandler接口,並實現了invoke方法
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
-
-
- public class Delegate implements InvocationHandler{
- private Factory factory;
-
- public Factory getFactory() {
- return factory;
- }
-
- public void setFactory(Factory factory) {
- this.factory = factory;
- }
-
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- return method.invoke(this.factory.getObject(), args);
- }
-
- }
ProxyUtils類:該類是一個工具類,負責生成一個httprequest對象的代理
- import java.lang.reflect.Proxy;
-
-
- public class ProxyUtils {
- public static HttpRequest getRequest(){
- HttpRequest request=new HttpRequestImpl();
- Delegate delegate=new Delegate();
- delegate.setFactory(Factory.getInstance());
- HttpRequest proxy=(HttpRequest) Proxy.newProxyInstance(request.getClass().getClassLoader(), request.getClass().getInterfaces(), delegate);
- return proxy;
- }
- }
TestThread類:該類用來模擬多線程調用controller的狀況,類中擁有一個靜態對象request。
- public class TestThread implements Runnable{
- private static HttpRequest request;
- public void init(){
- HttpRequestImpl requestimpl=new HttpRequestImpl();
- requestimpl.d=Math.random();
- Factory.getInstance().setObject(requestimpl);
- }
- @Override
- public void run() {
- System.out.println("*********************");
- init();
- request.service();
- System.out.println("*********************");
- }
- public static HttpRequest getRequest() {
- return request;
- }
- public static void setRequest(HttpRequest request) {
- TestThread.request = request;
- }
-
- }
main:測試類
- public class main {
-
-
- public static void main(String[] args) {
- HttpRequest request=ProxyUtils.getRequest();
-
- TestThread thread1=new TestThread();
- thread1.setRequest(request);
-
- TestThread thread2=new TestThread();
- thread2.setRequest(request);
-
- Thread t1=new Thread(thread1);
- Thread t2=new Thread(thread2);
-
- t1.start();
- t2.start();
- }
- }
thread1和thread2設置了同一個request對象,正常來講這兩個對象調用run方法時輸出的隨機值應該爲null(由於設置給這兩個對象的request並無設置d的值)。然而事實上這兩個線程在調用時不但輸出了隨機值並且隨機值還各不相同。這是由於request對象設置了代理,當調用request對象的service方法時,代理對象會從Threadlocal中獲取實際的request對象以替代調用當前的request對象。因爲httprequest對象在處理線程中保持不變,所以controller經過調用httprequest對象的方法可以獲取當前請求的參數。
以上都是一家之言,下面將經過展示springmvc源碼的形式證實以上的說法:dom
ObjectFactoryDelegatingInvocationHandler類:該類是AutowireUtils的一個私有類,該類攔截了除了equals、hashcode以及toString之外的其餘方法,其中的objectFactory是RequestObjectFactory實例。ide
- private static class ObjectFactoryDelegatingInvocationHandler implements InvocationHandler, Serializable {
-
- private final ObjectFactory objectFactory;
-
- public ObjectFactoryDelegatingInvocationHandler(ObjectFactory objectFactory) {
- this.objectFactory = objectFactory;
- }
-
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- String methodName = method.getName();
- if (methodName.equals("equals")) {
-
- return (proxy == args[0]);
- }
- else if (methodName.equals("hashCode")) {
-
- return System.identityHashCode(proxy);
- }
- else if (methodName.equals("toString")) {
- return this.objectFactory.toString();
- }
- try {
- return method.invoke(this.objectFactory.getObject(), args);
- }
- catch (InvocationTargetException ex) {
- throw ex.getTargetException();
- }
- }
- }
RequestObjectFactory類:其中currentReuqestAttributes負責從Threadlocal中獲取對象
- private static class RequestObjectFactory implements ObjectFactory<ServletRequest>, Serializable {
-
- public ServletRequest getObject() {
- return currentRequestAttributes().getRequest();
- }
-
- @Override
- public String toString() {
- return "Current HttpServletRequest";
- }
- }
既然須要從Threadlocal中獲取對象,那springmvc在什麼時候向Threadlocal設置了該對象呢?分別在以下兩個類中完成:RequestContextListener和FrameworkServlet。RequestContextListener負責監聽servletcontext,當servletcontext啓動時,RequestContextListener向Threadlocal設置了httprequest對象。FrameworkServlet是DispatchServlet的基類,tomcat會在運行過程當中啓動新的線程,而該線程中並無httprequest對象。所以servlet會在每次處理http請求的時候檢驗當前的Threadlocal中是否有httprequest對象,若是沒有則設置該對象。
FrameworkServlet經過布爾值previousRequestAttributes檢驗httprequest是否存在的代碼:
- protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
- long startTime = System.currentTimeMillis();
- Throwable failureCause = null;
-
-
- LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
- LocaleContextHolder.setLocaleContext(buildLocaleContext(request), this.threadContextInheritable);
-
-
- RequestAttributes previousRequestAttributes = RequestContextHolder.getRequestAttributes();
- ServletRequestAttributes requestAttributes = null;
- if (previousRequestAttributes == null || previousRequestAttributes.getClass().equals(ServletRequestAttributes.class)) {
- requestAttributes = new ServletRequestAttributes(request);
- RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
- }
-
- if (logger.isTraceEnabled()) {
- logger.trace("Bound request context to thread: " + request);
- }
-
- try {
- doService(request, response);
- }
- catch (ServletException ex) {
- failureCause = ex;
- throw ex;
- }
- catch (IOException ex) {
- failureCause = ex;
- throw ex;
- }
- catch (Throwable ex) {
- failureCause = ex;
- throw new NestedServletException("Request processing failed", ex);
- }
-
- finally {
-
- LocaleContextHolder.setLocaleContext(previousLocaleContext, this.threadContextInheritable);
- if (requestAttributes != null) {
- RequestContextHolder.setRequestAttributes(previousRequestAttributes, this.threadContextInheritable);
- requestAttributes.requestCompleted();
- }
- if (logger.isTraceEnabled()) {
- logger.trace("Cleared thread-bound request context: " + request);
- }
-
- if (logger.isDebugEnabled()) {
- if (failureCause != null) {
- this.logger.debug("Could not complete request", failureCause);
- }
- else {
- this.logger.debug("Successfully completed request");
- }
- }
- if (this.publishEvents) {
-
- long processingTime = System.currentTimeMillis() - startTime;
- this.webApplicationContext.publishEvent(
- new ServletRequestHandledEvent(this,
- request.getRequestURI(), request.getRemoteAddr(),
- request.getMethod(), getServletConfig().getServletName(),
- WebUtils.getSessionId(request), getUsernameForRequest(request),
- processingTime, failureCause));
- }
- }
- }
RequestContextListener在context初始化時經過requestInitialized函數向Threadlocal設置httprequest對象的代碼:
- public void requestInitialized(ServletRequestEvent requestEvent) {
- if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {
- throw new IllegalArgumentException(
- "Request is not an HttpServletRequest: " + requestEvent.getServletRequest());
- }
- HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();
- ServletRequestAttributes attributes = new ServletRequestAttributes(request);
- request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);
- LocaleContextHolder.setLocale(request.getLocale());
- RequestContextHolder.setRequestAttributes(attributes);
- }