Synchronizing on the session object may cause you all sorts of grief...or it may
not. It all depends on your container. The spec makes no guarantees about the
identity of the object returned by methods like PageContext.getSession or
HttpServletRequest.getSession. For example, here's a test JSP:

<%@ page contentType="text/plain" %>
<%
out.println("session:                " + session);
out.println("pageContext.getSession: " + pageContext.getSession());
out.println("request.getSession:     " + request.getSession(false));
out.println("request.getSession:     " + request.getSession(false));
%>

Here's the output from TC 4.1.24:

session:                [EMAIL PROTECTED]
pageContext.getSession: [EMAIL PROTECTED]
request.getSession:     [EMAIL PROTECTED]
request.getSession:     [EMAIL PROTECTED]

And that's just within the same thread! I'm pretty sure TC 4.1.29 does return
the same instance, but just remember it's not guaranteed.

Quoting Joe Germuska <[EMAIL PROTECTED]>:

> At 4:09 PM +0800 12/18/03, Andrew Hill wrote:
> >The sessions essentially just a sort of Map. Access to it may be
> threadsafe,
> >but the stuff thats in it is another matter entirely. Multiple requests
> >associated with the same session will execute simultaneously.
> 
> There's nothing in the specs that guarantee threadsafe access to 
> session attributes.
> 
> A pattern I've become quite fond of is to create a single object (we 
> call it a "shell", analogous to an operating system shell) which 
> encapsulates everything you want in session context for a given user; 
> then put just this object into session scope, and use methods on it 
> to do everything else.  This helps you apply synchronization where 
> appropriate.  There's still a risk of a race condition involving the 
> initial creation of the shell (assuming you do something like check 
> the session to see if there's a value under the key you use for the 
> shell) -- you can put that in a block synchronized on the session 
> object:
> 
> MyAppShell shell = null;
> synchronized (session)
> {
>    shell = (MyAppShell) session.getAttribute(SHELL_KEY);
>    if (shell == null)
>    {
>      shell = new MyAppShell ();
>      session.setAttribute(SHELL_KEY, shell);
>    }
> }
> 
> If the "shell" concept seems like high overhead to you, you can still 
> synchronize accesses on the session object along those lines; you may 
> just have more trouble keeping track of all the places it needs to 
> happen.
> 
> Joe
> 
> -- 
> Joe Germuska            
> [EMAIL PROTECTED]  
> http://blog.germuska.com    
>   "We want beef in dessert if we can get it there."
>    -- Betty Hogan, Director of New Product Development, National 
> Cattlemen's Beef Association

-- 
Kris Schneider <mailto:[EMAIL PROTECTED]>
D.O.Tech       <http://www.dotech.com/>

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to