当前位置:网站首页>Servlet learning diary 8 - servlet life cycle and thread safety
Servlet learning diary 8 - servlet life cycle and thread safety
2022-07-06 09:15:00 【herb. dr】
Catalog
One 、 There are four stages in the life cycle
2.2 How to ensure thread safety
One 、 There are four stages in the life cycle
1.1 Instantiation
When the user first accesses Servlet when , Called by container Servlet The constructor of creates a concrete Servlet object . You can also create instances as soon as the container starts . Use the following code to set Servlet Whether to create... When the server starts .
<load-on-starup>1</load-on-starup>
Be careful : Only once
1.2 initialization
In the initialization phase ,init() Method will be called . This method is javax.servlet.Servlet Interface . among , Method with a ServletConfig Object of type as parameter .
Be careful :init Method is executed only once
1.3 service
When the client has a request , The container will request ServletRequest And response ServletResponse Object turn Servlet, In the form of parameters to service Method .
This method executes multiple times
1.4 The destruction
When Servlet Containers (Tomcat) Stopping or restarting will lead to | Destroy from Servlet Object and call destroy Method .
destroy Method execution one Time

1.5 Code

package com.ha.servlet;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class LifeServlet implements Servlet{
public LifeServlet(){
System.out.println("1、 Instantiation ");
}
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("2、 initialization ");
}
public ServletConfig getServletConfig() {
return null;
}
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("3、 Receiving request , In response to the results ");
}
public String getServletInfo() {
return null;
}
public void destroy() {
System.out.println("4、 The destruction ");
}
}


perform shutdown.bat, This tomcat The destroyed content will be printed in a flash in the window of
Two 、 characteristic
2.1 Thread safety problem
Servlet After the visit , Will execute instantiation operation , Create a Servlet object . And we Tomcat The container can access the same server concurrently by multiple threads at the same time Servlet, If you modify a member variable in a method , There will be thread safety problems .
Code interpretation , More than two people visit at the same time :
package com.ha.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class SafeServlet extends HttpServlet {
private String message = "";
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// hypothesis 1、 Receiving parameters
//2、 Call business logic Get login results
message = " Login successful ";// Login failed !
PrintWriter printWriter = resp.getWriter();
printWriter.println(message);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
2.2 How to ensure thread safety
1、synchronized
Put the code with thread safety problems into the synchronization code block
2、 Realization singleThreadModel Interface
servlet Realization singleThreadModel After the interface , Every thread creates servlet example , In this way, each client request does not have the problem of sharing resources , however servlet Too inefficient to respond to client requests , So it has been eliminated .
3、 Use local variables as much as possible
2.3 Realization
1、 If locks are used

The efficiency of the code will be very low , Only one person is allowed to access
2、

3、
边栏推荐
- Redis之cluster集群
- Digital people anchor 618 sign language with goods, convenient for 27.8 million people with hearing impairment
- Redis cluster
- Intel Distiller工具包-量化实现1
- Leetcode刷题题解2.1.1
- Intel distiller Toolkit - Quantitative implementation 2
- [sword finger offer] serialized binary tree
- Kratos ares microservice framework (II)
- 【图的三大存储方式】只会用邻接矩阵就out了
- Redis之发布订阅
猜你喜欢

Improved deep embedded clustering with local structure preservation (Idec)

Reids之缓存预热、雪崩、穿透

不同的数据驱动代码执行相同的测试场景

Mise en œuvre de la quantification post - formation du bminf

ant-design的走马灯(Carousel)组件在TS(typescript)环境中调用prev以及next方法

Redis cluster

LeetCode41——First Missing Positive——hashing in place & swap

MySQL uninstallation and installation methods
![[text generation] recommended in the collection of papers - Stanford researchers introduce time control methods to make long text generation more smooth](/img/10/c0545cb34621ad4c6fdb5d26b495ee.jpg)
[text generation] recommended in the collection of papers - Stanford researchers introduce time control methods to make long text generation more smooth

什么是MySQL?MySql的学习之路是怎样的
随机推荐
KDD 2022 paper collection (under continuous update)
Using label template to solve the problem of malicious input by users
ant-design的走马灯(Carousel)组件在TS(typescript)环境中调用prev以及next方法
Redis之哨兵模式
[OC]-<UI入门>--常用控件-提示对话框 And 等待提示器(圈)
go-redis之初始化连接
Pytest之收集用例规则与运行指定用例
在QWidget上实现窗口阻塞
Redis之连接redis服务命令
LeetCode41——First Missing Positive——hashing in place & swap
Seven layer network architecture
LeetCode:394. String decoding
Leetcode: Jianzhi offer 03 Duplicate numbers in array
In depth analysis and encapsulation call of requests
Advanced Computer Network Review(3)——BBR
[daily question] Porter (DFS / DP)
LeetCode:498. Diagonal traversal
[OC]-<UI入门>--常用控件的学习
[Hacker News Weekly] data visualization artifact; Top 10 Web hacker technologies; Postman supports grpc
Redis之持久化实操(Linux版)