Spring does not guarantee thread-safe bean.
The default spring bean container is a single embodiment. ZFX agent for www.fx61.com/brokerlist/zfx.html, race conditions present when a single embodiment, i.e. there are security thread. The following examples
count class
Package constxiong.interview.threadsafe;
/ **
- Counting Class
- @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"?>
<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 {
static void main public (String [] args) {
Final the ClassPathXmlApplicationContext the ApplicationContext context = new new ( "spring_safe.xml");
for (int I = 0; I <10; I ++) {
new new the Thread () { br /> @ Override
public RUN void () {
counter = counter (counter) context.getBean ( "counter");
for (int J = 0; J <1000; J ++) {
counter.addAndPrint ();
}
}
} .start ();
}
}
}
print beginning and end result
9818
9819
9820
9821
9822
9823
9824
9825
a desired maximum value of 10000 should be printed
modify spring configuration files, the scope of the bean to the prototype
<? XML Version = "1.0" encoding = "UTF-. 8 "?>
<the bean ID = "counter" class = "constxiong.interview.threadsafe.Counter" scope = "the prototype"
</ Beans>
test result output 10
Spring JavaBean is a lightweight open container frame. Instead of using JavaBean EJB, and provides a wealth of enterprise applications, reduce the complexity of application development.
Lightweight: *** non-small resistance, what depends less resource consumption, easy deployment, different combinations of function selection jar
container: JavaBean achieve factory mode management by controlling the inverting (IOC) application configuration and separated from application code dependent
loosely coupled: by xml configuration bean or annotation to complete dependency injection
the AOP: xml configuration or by addition of the ability to annotate oriented programming complete cut features, such as: log, transaction. unified treatment .. the
ease of integration: by configuring and simple objects can be injected into an integrated other frameworks, such as Mybatis, Hibernate, Shiro ...
feature-rich: JDBC abstraction layer, transaction management, MVC, Java Mail, task scheduling, JMX , JMS, JNDI, EJB, dynamic languages, remote access, Web Service ...