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 for implementing features. In this case, the framework owns the servlet, and the servlet in turn uses your action objects. A well-designed framework 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.

The most glaring 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 is a poor design for a framework, since ensuring a class is thread-safe is both non-trivial to implement and easy to forget. This is an onerous and unnecessary burden for an application developer.

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
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -