First look at this piece of code:
@Servicepublic class Accountservice {private String message;public void Foo1 () {if (true) {this.message = "a";} else {This . Message = "B";}} public void Foo2 () {//Modify This.message code ...//...}}
If you're going to call Accountservice in @controller,
Accountservice.foo1 (); Model.addattribute (Accountservice.getmessage ());
Then there is the danger of thread safety.
The cause of the problem in spring, the bean's default scope is singleton, which means that there is only one instance of the bean in the container. In a Java Web environment, the Web server creates a thread for each request to process it. This way, calling the @service bean in @controller causes multiple threads to execute the @service method, such as thread A executes the Foo1 () method, and thread B executes the Foo2 () method. So the problem is, multiple threads reading and writing message member variables at the same time may let the GetMessage () method return the wrong value
Workaround 1. Change the scope of the @service bean to "request", i.e.:
@Service @scope ("Request") public class Accountservice {private String message;
This way, Spring creates a Accoutservice object for each request, and each thread has its own message variable, and there is no error. But the downside is that the overhead of creating @service beans tends to be large, which can cause program performance to degrade.
2. Use the Immutable object (Immuable object) to encapsulate the message variable to define the following classes:
Class Messagewrapper {private string message;public Messagewrapper (String msg) {this.message = msg;} Only the Get method public String GetMessage () {return this.message;}} is provided
Accountservice's Foo1 () method is modified as follows:
@Servicepublic class Accountservice {public Messagewrapper foo1 () {if (true) {return new Messagewrapper ("a");} else {retur N New Messagewrapper ("B");} // ... ...}
This can be a perfect way to avoid thread-safety problems without excessive overhead.
Spring MVC does not save state in @service beans