如何保證 Controller 的并發(fā)安全?

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èi)容包含Java基礎(chǔ)、JavaWeb、MySQL性能優(yōu)化、JVM、鎖、百萬并發(fā)、消息隊(duì)列、高性能緩存、反射、Spring全家桶原理、微服務(wù)、Zookeeper......等技術(shù)棧!
?戳閱讀原文領(lǐng)?。?/span>? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??朕已閱?
評(píng)論
圖片
表情

