Using a Request Filter to Limit the Load on Web Applications
Subject:   Threading issue
Date:   2004-03-25 04:08:22
From:   bazzargh
"Since the server will only be processing one request per session at a time, there may not be a need to worry about synchronizing access to objects in the session context. Only objects that could be accessed from multiple sessions might need to be synchronized."

I could be wrong here (I often am) but I think this is misleading; you /do/ always have to synchronize access to variables that you read and write in other threads, even if simultaneous access is impossible, in order to make the values visible.

Synchronization isn't just about locking. In java, locking and unlocking (the beginning and end of synch blocks) also provide some guarantees about visibility.

"if a thread is to perform an unlock action on any lock, it must first copy all assigned values in its working memory back out to main memory...a lock action acts as if it flushes all variables from the thread's working memory; before use they must be assigned or loaded from main memory." (JLS 17.6)

In fact if you have two servlet threads, t1, t2, processing requests on the same session, a request and response on t1 may complete before the request on t2 starts and t2 will /still/ not see the same session data, if no locking has taken place. The programming model would only be simplified if all actions on a session were forced to always reuse the same thread.

In practice its unlikely to be an issue - thread's don't run forever without synching for themselves - but its worth mentioning. You can do other things to minimize how long you need to lock the session, eg only store immutable objects in it.