`

Servlet之单例与线程安全

    博客分类:
  • JSP
阅读更多
一、Servlet 是单例吗

不是。
1、你可以用多个 URL 映射同一个 Servlet。这样就会出现多个实例。

2、看看 Servlet 定义:
引用

For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration.
如果 servlet 不是在分布式环境下(默认),servlet 容器必须使一个 servlet 实例对应一个 servlet 声明。

However, for a servlet implementing the SingleThreadModel(Deprecated) interface, the servlet container may instantiate multiple instances to handle a heavy request load and serialize requests to a particular instance.
然而,实现了 SingleThreadModel 接口的 Servlet,可以有多个实例。以处理繁重的请求,并且序列化 request 到特定的 servlet 实例。

public interface SingleThreadModel
Ensures that servlets handle only one request at a time.


结论:
虽然 Servlet 在多数情况下只有一个实例。但它并不是单例设计模式,即不是真正的单例。



二、Servlet 为什么是线程不安全的

基于 JVM 对多线程的支持,这样可以提高代码的执行效率。
不需要为每一个请求都要单独创建/销毁 Servlet(执行 init(), desdroy() )。
同一段代码可以在同一时间被多个请求同时执行。

Servlet 是普通的 Java 类,因此没有对其做线程安全的处理。


三、如何保证线程安全?(避免不安全)

但是,
Java 的类是线程安全的,只有在一种情况下:该类没有 instance variables.
即,没有(实例)变量时。

实例变量(instance properties)是声明在类中的变量,而不是声明在方法中的变量。

声明在方法中的变量是线程安全的,因为在执行该方法时,每一个线程都会在 Stack 中创建它们各自的变量。
因此,方法中的变量不存在线程不安全问题。


public class ExampleServlet extends HttpServlet {

    private Object thisIsNOTThreadSafe;

    protected void doGet(HttpServletRequest request, 
        HttpServletResponse response) throws ServletException, IOException {
        
        // BAD!! Shared among all requests!
        thisIsNOTThreadSafe = request.getParameter("foo");
        
        // OK, this is thread safe.
        Object threadSafeObj;        
        threadSafeObj = request.getParameter("foo"); 
    } 
}





四、拓展:Struts2 中的 Action 对象是单例吗?

不是。
当请求到来时,Web 容器为每一个请求创建一个 Request 和 Response 对象。
然后再创建一个线程,并把这两个对象的引用指向该线程。

Struts2 中的 Action 对象是 re-created 的,为每一个请求。并绑定到 Request 对象上,
作为 Request 对象的一个属性。这样就不存在线程不安全问题,因为每一个 Request 对象
只绑定一个线程。

注意:不要混淆 Struts DispatcherFilter 和 StrutsAction













-

Why is javax.servlet.SingleThreadModel deprecated?


The javadoc says why. SingleThreadModel was designed to be an easy solution to low-load concurrency, but it didn't even manage that:
引用

Note that SingleThreadModel does not solve all thread safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used. It is recommended that a developer take other means to resolve those issues instead of implementing this interface, such as avoiding the usage of an instance variable or synchronizing the block of the code accessing those resources.

If it can't achieve what it was designed for, it should not be used.


http://stackoverflow.com/questions/2551999
-







-
Why servlets are not thread safe?
http://stackoverflow.com/questions/9555842

How do servlets work? Instantiation, sessions, shared variables and multithreading
http://stackoverflow.com/questions/3106452

Is Servlet singleton?
http://stackoverflow.com/questions/11820840
--


Suppose, I have a webserver which holds numerous servlets. For information passing among those servlets I am setting session and instance variables.

Now, if 2 or more users send request to this server then what happens to the session variables? Will they all be common for all the users or they will be different for each user. If they are different, then how was the server able to differentiate between different users?

One more similar question, if there are n users accessing a particular servlet, then this servlet gets instantiated only the first time the first user accessed it or does it get instantiated for all the users separately? In other words, what happens to the instance variables?


--

ServletContext

When the servlet container (like Apache Tomcat) starts up, it will deploy and load all its web applications. When a web application is loaded, the servlet container creates the ServletContext once and keeps it in the server's memory. The web app's web.xml file is parsed, and each <servlet>, <filter> and <listener> found (or each class annotated with @WebServlet, @WebFilter and @WebListener respectively) is instantiated once and kept in the server's memory as well. For each instantiated filter, its init() method is invoked immediately.

When the servlet container shuts down, it unloads all web applications, invokes the destroy() method of all its initialized servlets and filters, and all ServletContext, Servlet, Filter and Listener instances are trashed.

When a Servlet has a <servlet><load-on-startup> or @WebServlet(loadOnStartup) value greater than 0, its init() method is also immediately invoked during startup. Those servlets are initialized in the same order specified by that value (1 -> 1st, 2 -> 2nd, etc). If the same value is specified for more than one servlet, then each of those servlets is loaded in the order they appear in the web.xml, or @WebServlet classloading. In the event the "load-on-startup" value is absent, the init() method will be invoked whenever the HTTP request hits that servlet for the very first time.

HttpServletRequest and HttpServletResponse

The servlet container is attached to a web server that listens for HTTP requests on a certain port number (port 8080 is usually used during development and port 80 in production). When a client (user with a web browser) sends an HTTP request, the servlet container creates new HttpServletRequest and HttpServletResponse objects and passes them through any defined Filter chain and, eventually, the Servlet instance.

In the case of filters, the doFilter() method is invoked. When its code calls chain.doFilter(request, response), the request and response continue on to the next filter, or hit the servlet if there are no remaining filters.

In the case of servlets, the service() method is invoked. By default, this method determines which one of the doXxx() methods to invoke based off of  request.getMethod(). If the determined method is absent from the servlet, then an HTTP 405 error is returned in the response.

The request object provides access to all of the information about the HTTP request, such as its headers and body. The response object provides the ability to control and send the HTTP response the way you want by, for instance, allowing you to set the headers and the body (usually with generated HTML content from a JSP file). When the HTTP response is committed and finished, both the request and response objects are recycled and made for reuse.

HttpSession

When a client visits the webapp for the first time and/or the HttpSession is obtained for the first time via request.getSession(), the servlet container creates a new HttpSession object, generates a long and unique ID (which you can get by session.getId()), and store it in the server's memory. The servlet container also sets a Cookie in the Set-Cookie header of the HTTP response with JSESSIONID as its name and the unique session ID as its value.

As per the HTTP cookie specification (a contract a decent web browser and web server have to adhere to), the client (the web browser) is required to send this cookie back in subsequent requests in the Cookie header for as long as the cookie is valid (i.e. the unique ID must refer to an unexpired session and the domain and path are correct). Using your browser's built-in HTTP traffic monitor, you can verify that the cookie is valid (press F12 in Chrome / Firefox 23+ / IE9+, and check the Net/Network tab). The servlet container will check the Cookie header of every incoming HTTP request for the presence of the cookie with the name JSESSIONID and use its value (the session ID) to get the associated HttpSession from server's memory.

The HttpSession stays alive until it has not been used for more than the timeout value specified in <session-timeout>, a setting in web.xml. The timeout value defaults to 30 minutes. So, when the client doesn't visit the web app for longer than the time specified, the servlet container trashes the session. Every subsequent request, even with the cookie specified, will not have access to the same session anymore; the servlet container will create a new session.

On the client side, the session cookie stays alive for as long as the browser instance is running. So, if the client closes the browser instance (all tabs/windows), then the session is trashed on the client's side. In a new browser instance, the cookie associated with the session wouldn't exist, so it would no longer be sent. This causes an entirely new HTTPSession to be created, with an entirely new session cookie begin used.

In a nutshell

The ServletContext lives for as long as the web app lives. It is shared among all requests in all sessions.
The HttpSession lives for as long as the client is interacting with the web app with the same browser instance, and the session hasn't timed out at the server side. It is shared among all requests in the same session.
The HttpServletRequest and HttpServletResponse live from the time the servlet receives an HTTP request from the client, until the complete response (the web page) has arrived. It is not shared elsewhere.
All Servlet, Filter and Listener instances live as long as the web app lives. They are shared among all requests in all sessions.
Any attribute that is defined in ServletContext, HttpServletRequest and HttpSession will live as long as the object in question lives. The object itself represents the "scope" in bean management frameworks such as JSF, CDI, Spring, etc. Those frameworks store their scoped beans as an attribute of its closest matching scope.
Thread Safety

That said, your major concern is possibly thread safety. You should now know that servlets and filters are shared among all requests. That's the nice thing of Java, it's multithreaded and different threads (read: HTTP requests) can make use of the same instance. It would otherwise be too expensive to recreate, init() and destroy() them for every single request.

You should also realize that you should never assign any request or session scoped data as an instance variable of a servlet or filter. It will be shared among all other requests in other sessions. That's not thread-safe! The below example illustrates this:


public class ExampleServlet extends HttpServlet {

    private Object thisIsNOTThreadSafe;

    protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
       
        // BAD!! Shared among all requests!
        thisIsNOTThreadSafe = request.getParameter("foo");
       
        // OK, this is thread safe.
        Object threadSafeObj;       
        threadSafeObj = request.getParameter("foo");
    }
}



-



转载请注明,
原文出处:http://lixh1986.iteye.com/blog/2355692











-
分享到:
评论

相关推荐

    Servlet线程安全的解决方法

    由于Servlet是单例模式实现的,这意味着每次请求都会复用同一个Servlet实例,因此,在多线程环境下,如何确保Servlet的线程安全就显得尤为重要。 #### 二、解决Servlet线程安全问题的方法 针对Servlet线程安全问题...

    1工作临时-servlet 多线程问题

    - 为了解决线程安全问题,有些情况下会将Servlet配置为单例模式,即整个应用只创建一个Servlet实例。但这并不能完全避免线程安全问题,因为单例Servlet的成员变量仍然会被多个请求线程共享。 5. **线程局部变量**...

    servlet是如何同时处理多个请求的

    由于多个线程可能同时访问同一实例,因此必须确保Servlet代码是线程安全的。如果Servlet内部有共享状态(如成员变量),需要采取同步机制,如`synchronized`关键字或使用线程局部变量来避免数据竞争。 2. **Servlet...

    servlet 模拟

    4. 单例模式:如果Servlet实例不需要为每个请求都创建,可以使用单例模式,并确保所有可能的共享状态都是线程安全的。 5. 无状态Servlet:如果Servlet不需要保持任何状态,那么它天生就是线程安全的,因为没有共享...

    Struts线程安全

    ”这是编写线程安全代码的重要原则之一。通过将实例变量转换为方法参数或局部变量,可以有效地避免线程安全问题。 #### 构造器的访问 构造器(new操作)是线程安全的,因为每次调用构造器都会创建一个新实例。这意味...

    实验12 单例模式与枚举.doc

    本专栏主要为Java程序设计(基础)实验报告和Java程序设计(进阶)...进阶篇有反射、泛型、注解、网络编程、多线程、序列化、数据库、Servlet、JSP、XML解析、单例模式与枚举。本专栏主要为Java入门者提供实验参考。

    2.单例模式(Singleton)1

    选择单例模式的实现方式应根据实际需求,考虑性能、线程安全和代码简洁性等因素。静态内部类方式通常被认为是既安全又简洁的选择。 **Spring的单例** 在Spring框架中,Bean默认就是单例模式,Spring会管理Bean的...

    Servlet网上售票问题引发线程安全问题的思考

    通过本文的分析,我们了解到Servlet在线程安全方面的挑战与解决方案。在实际的Web应用开发中,正确处理线程安全问题对于保证应用的稳定性和数据的准确性至关重要。开发者在设计和实现Web应用时,应该充分考虑到线程...

    Java面试题线程部分.docx

    线程与进程是不同的概念,进程是操作系统分配资源的基本单位,而线程是执行单元,一个进程中可以有多个线程共同执行任务。 用户线程和守护线程是线程的两种类型。用户线程是执行应用程序主要任务的线程,它们是系统...

    用户级线程的介绍,怎样实现多线程等等

    实现多线程的方式有多种,例如在一个servlet中全局保存请求,然后由单例servlet处理,或者将请求放入队列,由单线程调度处理。 用户级线程(User-Level Threads, ULTs)是由应用程序或线程库负责管理和调度的线程,...

    j2ee中使用线程的小DEMO

    例如,如果Servlet实例是单例模式的,那么其成员变量可能被多个线程共享,需要确保这些变量的访问是线程安全的,或者避免在Servlet中存储可变状态。 5. **EJB与线程**:Enterprise JavaBeans(EJB)提供了多种组件...

    原生Servlet与Spring Controller性能比较--Controller项目

    而Spring MVC通过Controller实例的单例模式或原型模式管理,自动处理线程安全,减轻了开发者负担。 4. **功能丰富度**:Spring Controller提供了丰富的功能,如数据验证、模型绑定、异常处理等,这些在原生Servlet...

    Servlet开发流程

    为提高Servlet的性能,可以考虑使用多线程处理请求、实现Servlet的单例模式(通过`load-on-startup`元素设置Servlet加载时机)以及使用过滤器(Filter)来拦截和预处理请求。 8. **Servlet 3.0及以上版本的新特性*...

    J2EE +单例模式 中文文档

    懒汉式单例在第一次被请求时才创建实例,但在多线程环境下可能存在线程安全问题。为了解决这个问题,引入了双重检查锁定(DCL)模式,它在保证线程安全的同时延迟实例化,兼顾了性能和资源利用。 静态内部类单例...

    servlet学习笔记

    在多线程环境下,Servlet是单例的,因此需要注意线程安全问题。全局变量可能被多个请求共享,需要加锁(如`synchronized(this)`)来确保线程安全。如果变量仅在当前请求内使用,可以直接在doGet或doPost方法中声明,...

Global site tag (gtag.js) - Google Analytics