zoukankan      html  css  js  c++  java
  • springmvc中request的线程安全问题

     

    SpringMvc学习心得(四)springmvc中request的线程安全问题

    标签: springspring mvc框架线程安全
     分类:

        servlet是单例的,而tomcat则是在多个线程中调用servlet的处理方法。因此如果servlet存在实例对象,那么就会引出线程安全的问题。而springmvc允许在controller类中通过@Autowired配置request、response以及requestcontext等实例对象。这种配置方法是否线程安全?答案是——这种配置方法是线程安全的,request、response以及requestcontext在使用时不需要进行同步。而根据spring的默认规则,controller对于beanfactory而言是单例的。即controller只有一个,controller中的request等实例对象也只有一个。然而tomcat依旧会以多线程的方式访问controller。这种做法似乎并不能保证线程安全。我们如何理解这一矛盾?

       在解释controller线程安全这一问题之前需要首先了解如下的一些问题和概念:

       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始终不变。读者可以亲自尝试,用以验证本人说法的真伪。

       2.Threadlocal类:该对象包含两个关键函数:set(Object obj)和get()。这两个函数与调用该函数的线程相关,set方法将某一对象“注入”到当前线程中,而get方法则是从当前线程中获取对象。

       3.InvocationHandler接口:这是springmvc保证request对象线程安全的核心。通过实现该接口,开发者能够在Java对象方法执行时进行干预,搭配Threadlocal就能够实现线程安全。

      下面将通过例子介绍springmvc如何保证request对象线程安全:

       Httprequest接口:

    [java] view plain copy
     
    1. public interface HttpRequest {  
    2.     public void service();  
    3. }  
       HttpRequestImpl类:对httprequest接口的具体实现,为了区别不同的HttpRequestImpl对象,本人为HttpRequestImpl设置了一个Double对象,如果不设置该对象,其默认为null
    [java] view plain copy
     
    1. public class HttpRequestImpl implements HttpRequest{  
    2.     public Double d;  
    3.     @Override  
    4.     public void service() {  
    5.         System.out.println("do some serivce, random value is "+d);  
    6.     }  
    7.   
    8. }  
       ThreadLocalTest类:负责向ThreadLocal设置对象和获取对象,本人设置ThreadLocal对象为static,因此ThreadLocalTest类中只能有一个ThreadLocal对象。
    [java] view plain copy
     
    1. public class ThreadLocalTest {  
    2.     public static ThreadLocal<HttpRequest> local=new ThreadLocal<HttpRequest>();  
    3.     public static void set(HttpRequest f){  
    4.         if(get()==null){  
    5.             System.out.println("ThreadLocal is null");  
    6.             local.set(f);  
    7.         }  
    8.     }  
    9.     public static HttpRequest get(){  
    10.         return local.get();  
    11.     }  
    12. }  
       Factory类:该类是一个工厂类并且是单例模式,主要负责向ThreadLocalTest对象中设置和获取对象
    [java] view plain copy
     
    1. public class Factory{  
    2.     private static Factory factory=new Factory();  
    3.     private Factory(){  
    4.           
    5.     }  
    6.     public static Factory getInstance(){  
    7.         return factory;  
    8.     }  
    9.     public HttpRequest getObject(){  
    10.         return (HttpRequest)ThreadLocalTest.get();  
    11.     }  
    12.     public void setObject(HttpRequest request){  
    13.         ThreadLocalTest.set(request);  
    14.     }  
    15. }  
      Delegate类:该类实现了InvocationHandler接口,并实现了invoke方法
    [java] view plain copy
     
    1. import java.lang.reflect.InvocationHandler;  
    2. import java.lang.reflect.Method;  
    3. import java.lang.reflect.Proxy;  
    4.   
    5.   
    6. public class Delegate implements InvocationHandler{  
    7.     private Factory factory;  
    8.       
    9.     public Factory getFactory() {  
    10.         return factory;  
    11.     }  
    12.   
    13.     public void setFactory(Factory factory) {  
    14.         this.factory = factory;  
    15.     }  
    16.   
    17.     @Override  
    18.     public Object invoke(Object proxy, Method method, Object[] args)  
    19.             throws Throwable {  
    20.         return method.invoke(this.factory.getObject(), args);  
    21.     }  
    22.       
    23. }  
       ProxyUtils类:该类是一个工具类,负责生成一个httprequest对象的代理
    [java] view plain copy
     
    1. import java.lang.reflect.Proxy;  
    2.   
    3.   
    4. public class ProxyUtils {  
    5.     public static HttpRequest getRequest(){  
    6.         HttpRequest request=new HttpRequestImpl();  
    7.         Delegate delegate=new Delegate();  
    8.         delegate.setFactory(Factory.getInstance());  
    9.         HttpRequest proxy=(HttpRequest) Proxy.newProxyInstance(request.getClass().getClassLoader(), request.getClass().getInterfaces(), delegate);  
    10.         return proxy;  
    11.     }  
    12. }  
       TestThread类:该类用来模拟多线程调用controller的情况,类中拥有一个静态对象request。
    [java] view plain copy
     
    1. public class TestThread implements Runnable{  
    2.     private static HttpRequest request;  
    3.     public void init(){  
    4.         HttpRequestImpl requestimpl=new HttpRequestImpl();  
    5.         requestimpl.d=Math.random();  
    6.         Factory.getInstance().setObject(requestimpl);  
    7.     }  
    8.     @Override  
    9.     public void run() {  
    10.         System.out.println("*********************");  
    11.         init();  
    12.         request.service();  
    13.         System.out.println("*********************");  
    14.     }  
    15.     public static HttpRequest getRequest() {  
    16.         return request;  
    17.     }  
    18.     public static void setRequest(HttpRequest request) {  
    19.         TestThread.request = request;  
    20.     }  
    21.       
    22. }  
       main:测试类
    [java] view plain copy
     
    1. public class main {  
    2.   
    3.     /** 
    4.      * @param args 
    5.      */  
    6.     public static void main(String[] args) {  
    7.         HttpRequest request=ProxyUtils.getRequest();  
    8.           
    9.         TestThread thread1=new TestThread();  
    10.         thread1.setRequest(request);  
    11.           
    12.         TestThread thread2=new TestThread();  
    13.         thread2.setRequest(request);  
    14.           
    15.         Thread t1=new Thread(thread1);  
    16.         Thread t2=new Thread(thread2);  
    17.           
    18.         t1.start();  
    19.         t2.start();  
    20.     }  
    21. }  
       thread1和thread2设置了同一个request对象,正常来说这两个对象调用run方法时输出的随机值应该为null(因为设置给这两个对象的request并没有设置d的值)。然而事实上这两个线程在调用时不但输出了随机值而且随机值还各不相同。这是因为request对象设置了代理,当调用request对象的service方法时,代理对象会从Threadlocal中获取实际的request对象以替代调用当前的request对象。由于httprequest对象在处理线程中保持不变,因此controller通过调用httprequest对象的方法能够获取当前请求的参数。

       以上都是一家之言,下面将通过展现springmvc源码的形式证明以上的说法:

       ObjectFactoryDelegatingInvocationHandler类:该类是AutowireUtils的一个私有类,该类拦截了除了equals、hashcode以及toString以外的其他方法,其中的objectFactory是RequestObjectFactory实例。

    [java] view plain copy
     
    1. private static class ObjectFactoryDelegatingInvocationHandler implements InvocationHandler, Serializable {  
    2.   
    3.         private final ObjectFactory objectFactory;  
    4.   
    5.         public ObjectFactoryDelegatingInvocationHandler(ObjectFactory objectFactory) {  
    6.             this.objectFactory = objectFactory;  
    7.         }  
    8.   
    9.         public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  
    10.             String methodName = method.getName();  
    11.             if (methodName.equals("equals")) {  
    12.                 // Only consider equal when proxies are identical.  
    13.                 return (proxy == args[0]);  
    14.             }  
    15.             else if (methodName.equals("hashCode")) {  
    16.                 // Use hashCode of proxy.  
    17.                 return System.identityHashCode(proxy);  
    18.             }  
    19.             else if (methodName.equals("toString")) {  
    20.                 return this.objectFactory.toString();  
    21.             }  
    22.             try {  
    23.                 return method.invoke(this.objectFactory.getObject(), args);  
    24.             }  
    25.             catch (InvocationTargetException ex) {  
    26.                 throw ex.getTargetException();  
    27.             }  
    28.         }  
    29.     }  
       RequestObjectFactory类:其中currentReuqestAttributes负责从Threadlocal中获取对象
    [java] view plain copy
     
    1. private static class RequestObjectFactory implements ObjectFactory<ServletRequest>, Serializable {  
    2.   
    3.         public ServletRequest getObject() {  
    4.             return currentRequestAttributes().getRequest();  
    5.         }  
    6.   
    7.         @Override  
    8.         public String toString() {  
    9.             return "Current HttpServletRequest";  
    10.         }  
    11.     }  
      既然需要从Threadlocal中获取对象,那springmvc在何时向Threadlocal设置了该对象呢?分别在如下两个类中完成:RequestContextListener和FrameworkServlet。RequestContextListener负责监听servletcontext,当servletcontext启动时,RequestContextListener向Threadlocal设置了httprequest对象。FrameworkServlet是DispatchServlet的基类,tomcat会在运行过程中启动新的线程,而该线程中并没有httprequest对象。因此servlet会在每次处理http请求的时候检验当前的Threadlocal中是否有httprequest对象,如果没有则设置该对象。

       FrameworkServlet通过布尔值previousRequestAttributes检验httprequest是否存在的代码:

    [java] view plain copy
     
    1. protected final void processRequest(HttpServletRequest request, HttpServletResponse response)  
    2.             throws ServletException, IOException {  
    3.   
    4.         long startTime = System.currentTimeMillis();  
    5.         Throwable failureCause = null;  
    6.   
    7.         // Expose current LocaleResolver and request as LocaleContext.  
    8.         LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();  
    9.         LocaleContextHolder.setLocaleContext(buildLocaleContext(request), this.threadContextInheritable);  
    10.   
    11.         // Expose current RequestAttributes to current thread.  
    12.         RequestAttributes previousRequestAttributes = RequestContextHolder.getRequestAttributes();  
    13.         ServletRequestAttributes requestAttributes = null;  
    14.         if (previousRequestAttributes == null || previousRequestAttributes.getClass().equals(ServletRequestAttributes.class)) {  
    15.             requestAttributes = new ServletRequestAttributes(request);  
    16.             RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);  
    17.         }  
    18.   
    19.         if (logger.isTraceEnabled()) {  
    20.             logger.trace("Bound request context to thread: " + request);  
    21.         }  
    22.   
    23.         try {  
    24.             doService(request, response);  
    25.         }  
    26.         catch (ServletException ex) {  
    27.             failureCause = ex;  
    28.             throw ex;  
    29.         }  
    30.         catch (IOException ex) {  
    31.             failureCause = ex;  
    32.             throw ex;  
    33.         }  
    34.         catch (Throwable ex) {  
    35.             failureCause = ex;  
    36.             throw new NestedServletException("Request processing failed", ex);  
    37.         }  
    38.   
    39.         finally {  
    40.             // Clear request attributes and reset thread-bound context.  
    41.             LocaleContextHolder.setLocaleContext(previousLocaleContext, this.threadContextInheritable);  
    42.             if (requestAttributes != null) {  
    43.                 RequestContextHolder.setRequestAttributes(previousRequestAttributes, this.threadContextInheritable);  
    44.                 requestAttributes.requestCompleted();  
    45.             }  
    46.             if (logger.isTraceEnabled()) {  
    47.                 logger.trace("Cleared thread-bound request context: " + request);  
    48.             }  
    49.   
    50.             if (logger.isDebugEnabled()) {  
    51.                 if (failureCause != null) {  
    52.                     this.logger.debug("Could not complete request", failureCause);  
    53.                 }  
    54.                 else {  
    55.                     this.logger.debug("Successfully completed request");  
    56.                 }  
    57.             }  
    58.             if (this.publishEvents) {  
    59.                 // Whether or not we succeeded, publish an event.  
    60.                 long processingTime = System.currentTimeMillis() - startTime;  
    61.                 this.webApplicationContext.publishEvent(  
    62.                         new ServletRequestHandledEvent(this,  
    63.                                 request.getRequestURI(), request.getRemoteAddr(),  
    64.                                 request.getMethod(), getServletConfig().getServletName(),  
    65.                                 WebUtils.getSessionId(request), getUsernameForRequest(request),  
    66.                                 processingTime, failureCause));  
    67.             }  
    68.         }  
    69.     }  
       RequestContextListener在context初始化时通过requestInitialized函数向Threadlocal设置httprequest对象的代码:
    [java] view plain copy
     
    1. public void requestInitialized(ServletRequestEvent requestEvent) {  
    2.         if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {  
    3.             throw new IllegalArgumentException(  
    4.                     "Request is not an HttpServletRequest: " + requestEvent.getServletRequest());  
    5.         }  
    6.         HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();  
    7.         ServletRequestAttributes attributes = new ServletRequestAttributes(request);  
    8.         request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);  
    9.         LocaleContextHolder.setLocale(request.getLocale());  
    10.         RequestContextHolder.setRequestAttributes(attributes);  
    11.     }  
     
     
  • 相关阅读:
    虚拟机中按键切回windows系统界面快捷键
    余数
    质数(素数)判断代码实现
    =excel========》函数使用
    python 正则表达式规则
    linux常用命令详解
    c指针
    visual studio 2015 开发时常见问题的解决方案
    python装饰器
    构造方法
  • 原文地址:https://www.cnblogs.com/developer-ios/p/5918999.html
Copyright © 2011-2022 走看看