Can this be due to the Singletion implementation of the bean? If yes, is there wouldn't changing to prototype solve my problem.
If you have a singleton bean, make sure that this bean does not maintain any state. This means, it should not have any field that is reinitialized based on some methods, except for the injection of another beans or resources that is done by Spring. This may cause concurrency issues, specially when the bean is used in several threads (in this case, to attend multiple requests done to your web service).
This is an example of a bad design for a Spring bean that will be used on multiple threads:
@Component
public class SingletonByDefaultBean {
private StringBuilder responseBuilder;
@Autowired
private FooService fooService;
public String methodUsedInSeveralThreads() {
//here you will have a concurrency issue
responseBuilder = new StringBuilder();
//write contents into the response
//...
//return the response
return responseBuilder.toString();
}
}
To solve this, you have two approaches:
Remove any state of the bean and move the attributes into method local variables:
@Component public class SingletonByDefaultBean { //private StringBuilder responseBuilder; @Autowired private FooService fooService; public String methodUsedInSeveralThreads() { StringBuilder responseBuilder = new StringBuilder(); //write contents into the response //... //return the response return responseBuilder.toString(); } }
Change the scope of the bean to prototype
@Component @Scope("prototype") public class SingletonByDefaultBean { private StringBuilder responseBuilder; @Autowired private FooService fooService; public String methodUsedInSeveralThreads() { responseBuilder = new StringBuilder(); //write contents into the response //... //return the response return responseBuilder.toString(); } }
What about initiating it with the new operator always?
Refer to this answer to know how you can create instances your classes manually and make them been managed by Spring. It is not that easy and I would recommend using these approaches only if you really understand what you're doing.