本文引用自:
http://www.codestyle.org/java/servlets/faq-Threads.shtml
Index
Servlet thread implementation
• Are servlets multi-threaded?
• What is a service thread and how do I create one?
• How does the container handle concurrent requests?
• Are you saying there is only one servlet instance for all requests?
• Are servlet requests handled first come, first served?
The single thread model
• What is the single threaded model?
• Why use SingleThreadedModel if servlets are multi-threaded?
• How do I implement the single threaded model?
• Should I use the SingleThreadedModel?
• How can I invoke servlet pooling with SingleThreadedModel?
Servlet thread management
• Can my servlet control the number of threads it accepts?
Servlet thread implementation
Q: Are servlets multi-threaded?
A: Yes, servlets are normally multi-threaded. The servlet container allocates a thread for each new request for a single servlet without any special programming. Each request thread for your servlet runs as if a single user were accessing it alone, but you can use static variables to store and present information that is common to all threads, like a hit counter for instance.
Q: What is a service thread and how do I create one?
A: The most common use of service threads are those used by a servlet container to handle the HTTP request-response process with a Java servlet. Servlet containers use an independent thread of execution so they can process many concurrent requests to many servlets and manage the overall performance of the server. Servlet requests are handled through the service() method, so they are named service threads, but other Java applications may use a similar service scheme.
Servlet containers automatically create or obtain service threads from a thread pool when a new HTTP request is received, so they do not need to be created explicitly in your servlet code.
Q: How does the container handle concurrent requests?
A: Servlet containers usually manage concurrent requests by creating a new Java thread for each request. The new thread is given an object reference to the requested servlet, which issues the response through the same thread. This is why it is important to design for concurrency when you write a servlet, because multiple requests may be handled by the same servlet instance.
Q: Are you saying there is only one servlet instance for all requests?
A: The way that servlet containers handle servlet requests is not prescribed to this extent; they may use a single servlet, they may use servlet pooling, it depends on the vendor's system architecture. New threads are not necessarily created for every servlet request but may be recycled through a worker thread pool for efficiency. The point is that you should write your servlet code to take account of a multi-threaded context regardless of the container implementation you happen to be using. In other words, you should adhere to the principle of write once, run anywhere.
Q: Are servlet requests handled first come, first served?
A: The use of a single servlet to handle multiple requests is usually done with Java threads. For each HTTP request the servlet container assigns a worker thread in which to execute the servlet code and a reference to the relevant servlet instance to call its service methods. The priority order by which the service threads are acquired and process the request depends on the detailed implementation of the servlet container. The natural principle is that it should be first come first served, but the actual execution sequence also depends on the thread scheduling scheme in the Java virtual machine.
Servlet containers normally limit the number of service threads that can be run concurrently, so pending requests are typically added to a queue.
Once a service thread is assigned to a request, the sequence in which the thread is executed depends on the thread scheduling system of the Java Runtime Environment (JRE). Threads can enter complex stop, start sequences in contention with other service threads, which is why your servlet code needs to be thread safe.
The single thread model
Q: What is the single threaded model?
A: Standard servlets are normally handled in a multi-threaded context in the servlet container. A number of virtually simultaneous requests for a single servlet could be handled by different threads using the same servlet instance. Any number of threads could access or modify the static and instance fields of a single servlet instance in an unpredictable sequence. This makes the instance fields of servlets as vulnerable to threading issues as static fields, and modification of shared resources must be considered carefully.
If your servlet implements the SingleThreadModel interface, it gets a guarantee from the servlet container that any single instance of the servlet will only be accessed by one thread at a time. The container either synchronizes access to the servlet's service() method, or uses a single instance of the servlet drawn from a pool.
The single threaded model adds a performance overhead to locking or managing servlet instances, so should not be used lightly. Generally, it is best to ensure synchronized access to servlet resources in your application code.
Q: Why use SingleThreadedModel if servlets are multi-threaded?
A: The SingleThreadedModel interface is used to ensure the safety of servlets that are vulnerable to thread safety issues. Normally, servlets should be written to run safely in a multi-threaded environment, and are executed in this context. The SingleThreadedModel is a way to override the normal multi-threaded execution context of the servlet container.
Q: How do I implement the single threaded model?
A: To create a servlet that a container will manage on a single threaded basis it must declare that it implements the javax.servlet.SingleThreadModel interface. This is a marker interface, there are no extra methods to fulfil, but this is sufficient for the container to identify the type and manage it accordingly.
public class SingleThreadServlet extends HttpServlet
implements SingleThreadModel {
// Standard HTTP servlet methods
}
The servlet container will typically synchronize access to a single instance of the servlet, or create a pool of servlet instances and allocate one request per instance.
Q: Should I use the SingleThreadedModel?
A: Not unless you have very good reason. The SingleThreadedModel interface has been deprecated, which means that it should not be used and may be removed in a later release of the Java servlet specification and Application Programming Interface (API). It has never really been advisable to implement the SingleThreadedModel, you should always aim to address thread safety issues in servlets using standard Java programming techniques.
Q: How can I invoke servlet pooling with SingleThreadedModel?
A: The SingleThreadedModel servlet specification does not require the creation of a pool of servlets. A single threaded model implementation may also synchronize access to a single servlet instance to achieve the same outcome, so that only one request is processed at a time. Apache Tomcat uses the synchronized approach, other servlet containers may use the pooled approach.
If you are concerned about the performance impact of synchronized access to the servlet instance, it would be preferable to re-design your servlet so that it does not depend on this mechanism at all. For example, you might create a synchronized block around the statements that are vulnerable to threading issues. By doing away with the single threaded model, you will minimise the performance impact of thread control.
Servlet thread management
Q: Can my servlet control the number of threads it accepts?
A: Your servlet should be designed to be thread safe and not to anticipate any limit to the number of concurrent requests it will receive. You should configure the number of concurrent requests to accept in your servlet container configuration. In Apache Tomcat this property is set in the server.xml file's Connector element, as below.
<Connector
className="org.apache.catalina.connector.http.HttpConnector"
minProcessors="3"
maxProcessors="20"
acceptCount="10"/>
• The acceptCount attribute sets the number of requests that can be queued waiting to be handled.
• The minProcessors attribute sets the number of request processors that are created when the servlet container starts up.
• The maxProcessors attribute sets the total number of request processors or that can be used to handle requests.
分享到:
相关推荐
Servlet和Struts Action是两种常见的Java Web开发组件,它们在多线程环境下运行时可能存在线程安全问题。线程安全是指在多线程环境中,一个类或者方法能够正确处理多个线程的并发访问,保证数据的一致性和完整性。 ...
针对Servlet线程安全问题,本文将介绍几种常见的解决策略: ##### 1. 实现SingleThreadModel接口 `SingleThreadModel`接口是一个过时但仍然有效的解决方案,它的设计初衷是为了确保每个请求在一个独立的线程中执行...
标题中的“1工作临时-servlet 多线程问题”表明我们即将探讨的是在实际工作中遇到的一个与Servlet和多线程相关的技术难题。Servlet是Java Web开发中用于处理HTTP请求的服务端组件,而多线程则涉及到并发编程,是...
#### 三、Servlet线程安全问题 线程安全问题主要发生在Servlet中使用实例变量时。当多个线程并发访问同一个Servlet实例时,如果这些线程试图同时修改实例变量,就可能发生数据不一致的情况。以下通过一个具体的示例...
当我们说一个Servlet是线程不安全的,意味着在多线程环境下,该Servlet的行为可能会出现问题,如数据混乱、竞态条件或死锁。 首先,让我们深入理解Servlet的工作原理。当一个HTTP请求到达Web服务器,服务器会创建一...
这篇博客"Servlet进阶的相关内容"可能深入探讨了Servlet的高级特性和实践应用。由于没有直接提供博客的具体内容,我会根据Servlet的常见进阶主题进行详细的阐述。 1. **Servlet生命周期**:Servlet在服务器启动时...
相比CGI(Common Gateway Interface),Servlet采用多线程模型,每个请求可以在单独的线程中处理,提高了效率。此外,Servlet可以利用Java的类库和API,如JDBC(Java Database Connectivity)来访问数据库,提供更...
本实例"Servlet常用语法Demo"旨在帮助初学者理解并掌握Servlet的基本用法和常见应用场景。 1. **Servlet生命周期** Servlet的生命周期包括加载、初始化、服务、销毁四个阶段。当服务器启动或第一次接收到对Servlet...
1. **线程安全**:由于Servlet默认是多线程的,开发者需要注意同步问题,避免在Servlet中使用全局变量或不线程安全的对象。 2. **性能优化**:可以通过实现`SingleThreadModel`接口使每个请求都创建新的Servlet实例...
此外,还支持异步处理,使得Servlet可以在处理请求时释放线程,提高服务器性能。 2. **servlet-api**: 这个包通常包含了Servlet API的JAR文件,包含了Servlet和JSP的相关接口和类,如`HttpServlet`、`Filter`等。在...
接下来,我们关注一个相关问题:在不重启TongWeb的情况下,能否重部署应用并实时生效。理想情况下,这将极大地提高运维效率。然而,由于上述资源管理问题,如果应用未在卸载时执行必要的清理操作,直接重部署可能会...
在讨论了Servlet线程安全问题的代码实现后,让我们来总结一下Servlet线程安全问题的几个要点: 1. 线程安全问题产生的原因:在多用户环境下,多个线程同时访问和修改共享资源(如Servlet中的`ticket`变量)时,如果...
JavaServlet帮助文档中的CHM文件是一个编译过的HTML帮助文档,它包含详细的API参考、教程、示例代码和常见问题解答,是开发者学习和查阅Servlet技术的重要资源。利用其内置的搜索功能,开发者可以快速找到所需的信息...
- **线程安全**:Servlet容器管理多个请求的并发访问,开发者需要考虑线程安全问题。 了解以上知识点后,你将能够更深入地理解Servlet在Java EE项目中的作用,以及如何在实践中有效地利用它来构建Web应用程序。...
5. **Servlet容器**:Servlet运行在Servlet容器(如Tomcat、Jetty)中,容器负责管理Servlet的生命周期,处理线程安全问题,并提供与Web服务器的集成。 6. **过滤器(Filter)**:Servlet API还提供了Filter接口,...
9. **多线程模型**:每个HTTP请求都会在单独的线程中由Servlet容器处理,这意味着Servlet需要考虑线程安全问题,尤其是在访问共享资源时。 10. **MVC模式与Servlet**:虽然Servlet主要用于处理请求和响应,但在实际...
Servlet 是一个运行在服务器端的单实例多线程的服务器端 Java 应用程序。理解 Servlet 的生命周期和接受参数信息是掌握 Servlet 技术的关键。 Servlet 的生命周期 Servlet 的生命周期可以分为四个阶段: 1. 初始...
这有助于防止线程安全问题,但可能会增加资源消耗。Servlet的实例数量可以通过应用程序的部署描述符进行配置。 总的来说,Servlet 2.3规范是Java Web开发中的基石,它定义了Servlet如何工作、如何与Web容器交互以及...
Servlet是Java平台上的一个核心组件,用于构建动态Web应用程序。Servlet规范定义了Servlet接口和相关的API,以便开发者能够创建服务器端...在实际开发中,结合规范和API文档,可以解决许多常见的问题,并提升代码质量。