Issue
I have just started learning Spring. I am confused with some simple concept of concurrency.
I have a class containing only 1 field uid
:
@Service("Class1")
@Data
public class Class1 {
private String uid;
}
And I have request mapper with Class1
Autowired in it.
@RestController
@RequestMapping("/web")
@Scope("session")
public class Web {
@Autowired
Class1 class1;
@GetMapping("/hello")
public String sayHello(@RequestParam(value = "myName", defaultValue = "World") String name) {
class1.setUid(name);
try{
Thread.sleep(5000);
}
catch (InterruptedException e){
}
return String.format("Hello %s and uid %s!", name,class1.getUid());
}
}
Now if I hit two request at the same time with two different parameters say, myName=name1
and myName=name2
, the uid is shown same in both the requests. But i think it should be equal to that particular name which is being passed.
I want to assign uid
equal to the name which is being passed. How cannot be there 2 different instances of Class1
in both the request? Why is this concurrency happening?
I know Spring handle 2 different sessions by generating 2 different threads. But my concern is that both the threads use same bean. But i want different instance for different sessions. What is the proper way to do so?
Solution
I'm not sure if this is the issue, but at first glance I could relate this to the fact that the default(implicitly used) scope is Singleton, which means there is only one instance of bean (in your case the service bean). Usually, to handle state inside of the beans it is better to use @RequestScope for the service class (if you want to store the state there), which will create bean instance exactly for each particular request.
Answered By - Andriy Zhuk
Answer Checked By - Clifford M. (JavaFixing Volunteer)