Threads in Spring

RN. picture RN. · Apr 23, 2009 · Viewed 9.6k times · Source

I have a Web application using spring and hibernate and struts (it runs on Tomcat)

The call sequence is something like this...

Struts action calls spring service bean which in turn calls Spring DAO bean. The DAO implementation is a Hibernate implementation.

The question is Would all my spring beans be running in the same thread ? Can I store something in the ThreadLocal and get it in another bean?

I am quite sure this would not work in Stateless Session Bean. The EJB container can (or will) spawn a new thread for every call to the session bean

Will the spring container do the same? i.e. run all beans in the same thread ?

When I tried a JUnit test - I got the same id via Thread.currentThread().getId() in the Test Case and the two beans- which leads me to believe there was only one thread in action

Or is the behavior unpredictable? Or will it change when running on Tomcat server ?

Clarification I do not wish to exchange data between two threads. I want to put data in the ThreadLocal and be able to retrieve it from all beans in the call stack. This will work only if all beans are in the same thread

Answer

A_M picture A_M · Apr 23, 2009

Spring doesn't spawn the threads. Tomcat does. Spring is just creating and wiring up the objects for you.

Each request from the browser is processed in one request. It is Tomcat that handles the request. It is Tomcat that creates the thread to process the request.

Assuming you have just created a singleton bean in Spring called "X". Then the same instance of X is used by all requests.

The Spring beans don't live in a thread. They are just allocated on the heap.