如何保證 Controller 的并發(fā)安全?
點(diǎn)擊上方“碼農(nóng)突圍”,馬上關(guān)注 這里是碼農(nóng)充電第一站,回復(fù)“666”,獲取一份專屬大禮包 真愛,請(qǐng)?jiān)O(shè)置“星標(biāo)”或點(diǎn)個(gè)“在看” 來源: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并發(fā)安全的解決辦法
盡量不要在 Controller 中定義成員變量 ;
@Scope(“prototype”) ,將Controller設(shè)置為多例模式。@Controller
@Scope(value="prototype")
public?class?TestController?{
????private?int?num?=?0;
????@RequestMapping("/addNum")
????public?void?addNum()?{
????????System.out.println(++num);
????}
}
Controller 中使用 ThreadLocal 變量。每一個(gè)線程都有一個(gè)變量的副本。
public?class?TestController?{
????private?int?num?=?0;
????private?final?ThreadLocal??uniqueNum?=
?????????????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 , 得到的結(jié)果都是1。(完)
碼農(nóng)突圍資料鏈接
1、臥槽!字節(jié)跳動(dòng)《算法中文手冊(cè)》火了,完整版 PDF 開放下載!
2、計(jì)算機(jī)基礎(chǔ)知識(shí)總結(jié)與操作系統(tǒng) PDF 下載
3、艾瑪,終于來了!《LeetCode Java版題解》.PDF
4、Github 10K+,《LeetCode刷題C/C++版答案》出爐.PDF歡迎添加魚哥個(gè)人微信:smartfish2020,進(jìn)粉絲群或圍觀朋友圈
評(píng)論
圖片
表情

