Raedwald
Raedwald

Reputation: 48684

Must Spring component classes be thread-safe

If you use Spring, must your component classes (@Controller, @Service, @Repository) be thread safe? Or does Spring use them in a thread-safe manner so you don't have to worry about thread safety?

That is, if I have a @RequestMapping method in my @Controller, could that method be called simultaneously for the same controller object by more than one thread?

(This has sort-of been asked before, but not answered as such).

Upvotes: 40

Views: 34125

Answers (4)

Simon
Simon

Reputation: 140

A Spring component, as well as another class, must be thread-safe if it can be used concurrently by a number of threads. A Spring component is a singleton by default and can be called from different threads. From this point of view, its STATE should be thread-safe. From another hand, singleton Spring beans, normally serve requests in a call stack of a thread from a pool of thread. Normally a Spring component has fields, which values are injected interfaces or properties. The only need to take care of safety is the case when state objects are kept in a bean. Usually, it is not used due to servers are load-balanced and a state is kept in a cache or in a database. Singleton bean, thus, should be used as a set of functions, which transfers data as arguments of a related method, and its fields should not keep business data, but just injected beans, which serve call progress. Spring's controller is an example. Its methods are called by a Tomcat's threads, way of controllers methods mapping, and all the calls stack is done in one thread. Controller's method calls DAO methods and returns results in the same thread. A Session normally is persisted from session to session and this is handled by Spring. So, except for rare cases, there is no need to take care of thread safety.

Upvotes: -1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

Given

@Controller
public class MyController {
    @RequestMapping(value = "/index")
    public String respond() {
        return "index";
    }
}

Spring will create an instance of MyController. This is because Spring parses your configuration, <mvc:annotation-driven>, sees @Controller (which is like @Component) and instantiates the annotated class. Because it sees @RequestMapping as well, it generates a HandlerMapping for it, see the docs here.

Any HTTP requests the DispatcherServlet receives will be dispatched to this controller instance through the HandlerMapping registered before, calling respond() through java reflection on that instance.

If you have instance fields like

@Controller
public class MyController {
    private int count = 0;
    @RequestMapping(value = "/index")
    public String respond() {
        count++;
        return "index";
    }
}

count would be a hazard, because it might be modified by many threads and changes to it might be lost.

You need to understand how Servlet containers work. The container instantiates one instance of your Spring MVC DispatcherServlet. The container also manages a pool of Threads which it uses to respond to connections, ie. HTTP requests. When such a request arrives, the container picks a Thread from the pool and, within that Thread, executes the service() method on the DispatcherServlet which dispatches to the correct @Controller instance that Spring registered for you (from your configuration).

So YES, Spring MVC classes must be thread safe. You can do this by playing with different scopes for your class instance fields or just having local variables instead. Failing that, you'll need to add appropriate synchronization around critical sections in your code.

Upvotes: 58

Codo
Codo

Reputation: 78835

By default, controllers are singletons and thus must be thread-safe. However, you can configure the controllers to be request or session scoped, i.e.:

@Controller
@Scope("session")
public class MyController {

    ...
}

Controllers with session scope can be helpful for managing session state. A good description of different patterns can be found in Using Sessions in Spring-MVC (including "scoped-proxies") and in How to get Session Object In Spring MVC. Some of the presented patterns require request scope.

The request scope is useful as well if you have data that you cannot afford to calculate more than one per request.

Upvotes: 1

duffymo
duffymo

Reputation: 308763

Yes, of course.

It's best if those are stateless, which makes them thread safe by default. If there's no shared, mutable state there's no problem.

Upvotes: 0

Related Questions