봄의 콩은 스레드로부터 안전한가요?
Spring은 Bean의 스레드 안전성을 보장하지 않습니다.
스프링 컨테이너의 Bean은 기본적으로 싱글톤입니다. 싱글톤에 경쟁 조건이 있으면 스레드 안전 문제가 발생합니다. 아래 예시
Counting class
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>
Test class
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#🎜🎜 #
스프링 구성 파일을 수정하고 Bean의 범위를 프로토타입으로 변경<?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>
즉, 각 스레드 A Counter 개체가 생성되고 스레드 내에서 독립적으로 계산되므로 스레드 안전 문제가 없습니다. 그러나 이것은 우리가 원하는 결과가 아닙니다. 10000이 인쇄됩니다.
위 내용은 Spring의 Bean은 스레드로부터 안전합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!