dagblog.
← Archive

Synchronizing access to objects in an HTTP session


I’ve started reading Java Concurrency in practice, and somewhere between pages it occurred to me that most web applications I’ve worked on were thread-safe only on the surface. The weak point was the objects stored in the session, which different threads could use at the same time.

The Servlet specification puts it plainly.

Multiple servlets executing request threads may have active access to the same session object at the same time. The container must ensure that manipulation of internal data structures representing the session attributes is performed in a thread safe manner. The Developer has the responsibility for thread safe access to the attribute objects themselves.

The risk grew as AJAX-based applications took off. You could have several asynchronous calls running in parallel that typically converged on data held in the session. It may be easy to miss, but poorly managed concurrent access to session data can leave an application in quite unexpected states. In the best case, it ends with something like a seemingly inexplicable NullPointerException. Indiscriminately synchronizing everything can also make an application scale poorly.

When we really need mutual exclusion, meaning serialized access to data within the session, we should think about the scope of the lock. If I’m remembering right, JBoss Seam can synchronize each request on its associated session. In many cases that lock is needlessly broad. We can instead synchronize directly on the object that might be shared between threads.

If all we need is proper visibility between threads and concurrent access is fine, we can use volatile or an appropriate abstraction in the code. For a map, for instance, we can choose ConcurrentHashMap.

I suspect that in many cases people either don’t think about synchronizing objects shared through a session or quietly ignore the issue because the consequences aren’t obvious. I’d love to know whether you handle it in your own applications or leave it to chance on the grounds that things will somehow work out.

Medium version

Related articles

Related CZ Podcast episodes