春の豆スレッドセーフ?
春はスレッドセーフBeanを保証するものではありません。
デフォルトスプリング豆容器は、単一の実施形態です。単一の実施形態の競合状態が存在する場合、すなわち、セキュリティスレッドがあります。次の例
カウントクラス
パッケージconstxiong.interview.threadsafe。
/ **
*クラスカウント
* @author ConstXiong
* @date 2019年7月16日夜02時35分40秒
* /
パブリッククラスカウンター{
プライベートint型のカウント= 0;
ます。public void addAndPrint(){
{試します
Thread.sleep(10)。
}キャッチ(InterruptedExceptionある電子){
e.printStackTrace();
}
System.out.println(++カウント)。
}
}
春のプロファイル
xmlns:XSI = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:コンテキスト= "http://www.springframework.org/schema/context"
XSI:のschemaLocation =」
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd ">
テストカテゴリ
パッケージconstxiong.interview.threadsafe。
輸入org.springframework.context.ApplicationContext;
輸入org.springframework.context.support.ClassPathXmlApplicationContext;
パブリッククラスCounterTest {
パブリック静的無効メイン(文字列[] args){
最終のApplicationContextコンテキスト=新しいClassPathXmlApplicationContext( "spring_safe.xml")。
{(; iが10 <I ++はiが0 = INT)のために
新しいスレッド(){
@オーバーライド
ます。public void実行(){
カウンタカウンタ=(カウンタ)context.getBean( "カウンタ")。
(INT J = 0; J <1000; J ++)のために{
counter.addAndPrint();
}
}
}。開始();
}
}
}
印刷結果が始まりと終わり
1つの無錫中絶費用http://www.xasgfk120.com/
5
7
4
2
6
3
8
9
。
。
。
9818
9819
9820
9821
9822
9823
9824
9825
予想される最大値は10 000でなければなりませんプリントアウト
春の構成ファイルを変更し、豆のプロトタイプのスコープを変更します
xmlns:XSI = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:コンテキスト= "http://www.springframework.org/schema/context"
XSI:のschemaLocation =」
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd ">
試験結果出力10~1000
つまり、各スレッドは、独自のスレッドカウント内のカウンタオブジェクトを作成し、スレッドの安全性の問題は存在しません。しかし、私たちが望む結果、10000をプリントアウトではありません。
豆と豆のスコープと春の豆スレッドセーフな管理が作成されるので、レースの存在に関連する環境条件の使用は、春にはスレッドセーフな豆を保証するものではありませんどこ。