Thread safety in web apps

In a web application, you should verify that the following items are safe for operation in a multi-threaded environment:

Many applications use a framework. Frameworks usually define the servlet class, and the thread-safety of those servlets will be explicitly stated by a well-documented framework. Many frameworks require the application developer to define actions or controllers for implementing features. In this case, the framework owns the servlet, and the servlet in turn uses your action/controller objects. Some frameworks will create your action objects on the fly, on the single thread assigned to handle a single request. This in turn means that your actions will be confined to a single thread; thus, in this case, your action classes will have no need for thread-safety.

An example of a framework which violates this rule is Struts 1. In Struts 1, your actions must be designed for operation in a multi-threaded environment. This can be considered a defect, since ensuring a class is thread-safe is both non-trivial to implement and easy to forget.

A second example of a framework that can insist on thread-safety is Spring. In Spring, by default, objects managed by the Dependency Injection container are singletons, and need to be thread-safe. If this bothers you, then at least you have the choice in Spring of changing the "scope" in which objects are used.

In the case of servlet filters, a framework is not usually used when defining them. In this case, you have to be careful that your servlet filter class is indeed safe for operation in a multi-threaded environment.

For objects placed in either application scope or session scope, the simplest design is to ensure that the object is immutable, such that external synchronization is never necessary.

It's clear to most people that objects placed in application scope will be accessed by more than one thread. However, even objects placed in session scope can also be used by more than one thread. From the Servlet Specification:

"Multiple servlets executing request threads may have active access to a single session object at the same time. The Developer has the responsibility for synchronizing access to session resources as appropriate."

Here are some ways in which multiple threads might access the same session:

See Also :
Immutable objects
Document thread safety