The spring bean thread-safe?
Spring does not guarantee thread-safe bean.
The default spring bean container is a single embodiment. When a single embodiment race condition exists, i.e. there are security thread. The following examples
Counting Class
package constxiong.interview.threadsafe;
/**
* Class Counting
* @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 Profiles
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">
Test category
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();
}
}
}
Print results beginning and end
1 Wuxi abortion costs http://www.xasgfk120.com/
5
7
4
2
6
3
8
9
.
.
.
9818
9819
9820
9821
9822
9823
9824
9825
Print out the expected maximum should be 10 000
Modify spring configuration file, change the scope of the bean prototype
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">
Test result output 10 1000
That is, each thread creates a Counter object within its own thread count, thread-safety problem does not exist. But it is not the result we want, print out 10000.
So the spring bean thread-safe management with bean and bean's scope is created where the use of environmental conditions relating to the existence of race, spring does not guarantee thread-safe bean.