如何保证 Controller 的并发安全?
点击上方“码农突围”,马上关注 这里是码农充电第一站,回复“666”,获取一份专属大礼包 真爱,请设置“星标”或点个“在看” 来源:toutiao.com/article/6927297421139706376
Each incoming request requires a thread for the duration of that request. If more simultaneous requests are received than can be handled by the currently available request processing threads, additional threads will be created up to the configured maximum (the value of the maxThreads attribute). If still more simultaneous requests are received, they are stacked up inside the server socket created by the Connector, up to the configured maximum (the value of the acceptCountattribute). Any further simultaneous requests will receive "connection refused" errors, until resources are available to process them. —— https://tomcat.apache.org/tomcat-7.0-doc/config/http.html
Controller不是线程安全的
@Controller
public class TestController {
private int num = 0;
@RequestMapping("/addNum")
public void addNum() {
System.out.println(++num);
}
}
首先访问 http:// localhost:8080 / addNum
,得到的答案是1;再次访问 http:// localhost:8080 / addNum
,得到的答案是 2。
Controller并发安全的解决办法
尽量不要在 Controller 中定义成员变量 ;
@Scope(“prototype”)
,将Controller设置为多例模式。@Controller
@Scope(value="prototype")
public class TestController {
private int num = 0;
@RequestMapping("/addNum")
public void addNum() {
System.out.println(++num);
}
}
Controller 中使用 ThreadLocal 变量。每一个线程都有一个变量的副本。
public class TestController {
private int num = 0;
private final ThreadLocaluniqueNum =
new ThreadLocal() {
@Override protected Integer initialValue() {
return num;
}
};
@RequestMapping("/addNum")
public void addNum() {
int unum = uniqueNum.get();
uniqueNum.set(++unum);
System.out.println(uniqueNum.get());
}
}
http:// localhost:8080 / addNum
, 得到的结果都是1。(完)
码农突围资料链接
1、卧槽!字节跳动《算法中文手册》火了,完整版 PDF 开放下载!
2、计算机基础知识总结与操作系统 PDF 下载
3、艾玛,终于来了!《LeetCode Java版题解》.PDF
4、Github 10K+,《LeetCode刷题C/C++版答案》出炉.PDF欢迎添加鱼哥个人微信:smartfish2020,进粉丝群或围观朋友圈
评论