5

I have this new mvc project where all beans are default scoped(no prototype or session). with single application context.

i want to know by making all beans to be default scoped are we trying to achieve the whole application to be run in single thread?

if so will that make each httprequest(from multiple or same sessions) to be queued until the previous one completes?How to avoid such scenario any advice or link would be helpful.

I am relatively new to spring and java development.

shadowfox
  • 581
  • 1
  • 7
  • 20
  • 2
    I dont think ur httprequest will get queued and wait for previous ones to complete. Please go through spring documentation more. all ur questions are answered there already :-) – Arun Aug 27 '12 at 18:21

2 Answers2

11

Because Spring beans are typically stateless, you can safely call them from multiple threads. That's how your application works: there is only one instance of every controller, service, DAO, etc. But your servlet container (through Spring) calls these beans from multiple threads - and it's completely thread safe.

In fact in plain servlets the situation is the same - there is only instance of each servlet and it can be accessed by infinite number of threads. As long as this servlet is stateless or properly synchronized.

Do not confuse Spring with stateless session beans in that are pooled and each client gets its own instance from the pool.1

1 - In fact that's a bit dumb - since the beans are stateless by the definition, there is no point in pooling them and preventing concurrent access...

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • Related to your comment about the EJB specification: why pooling is needed? There are Java EE parts that are not guaranteed to work after they throw an Exception (e.g [Exception handling in Hibernate/JPA](http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch13.html#transactions-demarcation-exceptions)). Given that, the container should 1. either reinject that failed component in your bean (e.g reinject `EntityManager` in the EJB instance) 2. or simply throw the bean away and create another one. The second solution was chosen. How is this case treated in Spring? – V G Jun 19 '15 at 13:58
  • I believe this is a common mistake and also big difference to Spring beans. Stateless EJBs are meant as stateless from clients point of view, meaning that it does not matter which bean serves the clients request. On the other hand, these beans can hold resources, which are expansive to create, or other internal state. Therefore pooling offers performance benefits as well as thread safety. – Kousalik Jan 31 '16 at 19:34
2

Singleton means that the there will be only one instance of each bean. Generally, such beans are processing elements that carry no state. The methods called on them are passed the context which contains the inputs to work on. Hence the method calls on such singleton beans are inherently thread-safe.

Vikdor
  • 23,934
  • 10
  • 61
  • 84