ホームページ  >  記事  >  Java  >  春の豆は安全ですか?

春の豆は安全ですか?

(*-*)浩
(*-*)浩転載
2019-09-12 16:14:593057ブラウズ

春の豆はスレッドセーフですか?

春の豆は安全ですか?

#Spring は Bean スレッドの安全性を保証しません。

デフォルトでは、Spring コンテナ内の Bean はシングルトンです。シングルトンで競合状態が発生すると、スレッドの安全性の問題が発生します。 以下の例のように

Countingクラス

package constxiong.interview.threadsafe;
 
/**
 * 计数类
 * @author ConstXiong
 * @date 2019-07-16 14:35:40
 */
public class Counter {
 
	private int count = 0;
	
	public void addAndPrint() {
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(++count);
	}
}

Spring設定ファイル

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="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">
        
	<bean id="counter" class="constxiong.interview.threadsafe.Counter" />
	
</beans>

テストクラス

package constxiong.interview.threadsafe;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class CounterTest {
	
	public static void main(String[] args) {
		final ApplicationContext context = new ClassPathXmlApplicationContext("spring_safe.xml");
 
		for (int i = 0; i < 10; i++) {
			new Thread(){
				@Override
				public void run() {
					Counter counter = (Counter)context.getBean("counter");
					for (int j = 0; j < 1000; j++) {
						counter.addAndPrint();
					}
				}
			}.start();
		}
		
	}
	
}

結果の先頭と末尾を出力します

1
5
7
4
2
6
3
8
9
.
.
.
9818
9819
9820
9821
9822
9823
9824
9825

出力されると予想される最大値は 10000 です

#Spring 構成ファイルを変更し、Bean スコープを変更しますtoprototype

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="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">
	<bean id="counter" class="constxiong.interview.threadsafe.Counter" scope="prototype"/>
</beans>

テスト結果は 10 1000

を出力します。つまり、各スレッドは Counter オブジェクトを作成し、スレッド内で独立してカウントするため、スレッドの安全性の問題はありません。しかし、これは私たちが望む結果ではなく、10000 が出力されます。 春の豆は安全ですか?

したがって、Spring によって管理される Bean のスレッド セーフは、Bean の作成スコープと Bean が配置されている使用環境に競合状態があるかどうかに関係しており、Spring は Bean のスレッド セーフを保証できません。

以上が春の豆は安全ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はcsdn.netで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。