This forum is now a read-only archive. All commenting, posting, registration services have been turned off. Those needing community support and/or wanting to ask questions should refer to the Tag/Forum map, and to http://spring.io/questions for a curated list of stackoverflow tags that Pivotal engineers, and the community, monitor.

newbie question - Servlets and singleton beans

Aug 22nd, 2005, 04:42 PM

I am new to servlets and spring. I have 2 apps that are talking with each other using http request/request. App1 is C++ legacy app and App2 is developed using spring. In my App2 I have a servlet that extends FrameworkServlet. In my context defintion I have a singleton bean "ProcessorBean", that gets called by the servlet to process the http request and persist data to DB. My questiion is when http requests are received by the servlet are they queued up and the same instance of the ProcessorBean is called to process each request? Or does the BeanFactory creates several instances of the ProcessorBean? My concern is that since my ProcessorBean is modifying records in DB, if serveral instances of them are running I should be worried about getting concurrency issues.

Any help of ideas about alternative implementaions would be appreciated.

Default all beans in the ApplicationContext in Spring are singleton. Every Servlet has access to the ApplicationContext (if you have set it up correct), so everytime a bean is required, the servlet will get the same bean, time after time.

And normally concurrency control with databases is solved by using transactions. Usually concurrency control to the database is not a big issue.

Comment

If the bean is created with the singleton property set to true (which it will be by default) it will only create one copy per application context.

This is typically not a problem since most Spring database classes are thread safe. SqlBatchUpdate is one of the few that isn't (and this is stated in the documentation). But in general its easy to design Spring database access classes to be thread safe.