Is synchronization within an HttpSession feasible?

19,713

Solution 1

Here is my own solution:

It seems that the session object itself is not always the same as it depends on the implementation of the servlet container (Tomcat, Glassfish, ...) and the getSession() method might return just a wrapper instance.

So it is recommended to use a custom variable stored in the session to be used as locking object.

Here is my code proposal, feedback is welcome:

somewhere in a Helper Class, e.g. MyHelper:

private static final Object LOCK = new Object();

public static Object getSessionLock(HttpServletRequest request, String lockName) {
    if (lockName == null) lockName = "SESSION_LOCK";
    Object result = request.getSession().getAttribute(lockName);
    if (result == null) {
        // only if there is no session-lock object in the session we apply the global lock
        synchronized (LOCK) {
            // as it can be that another thread has updated the session-lock object in the meantime, we have to read it again from the session and create it only if it is not there yet!
            result = request.getSession().getAttribute(lockName);
            if (result == null) {
                result = new Object();
                request.getSession().setAttribute(lockName, result);
            }
        }
    }
    return result;
}

and then you can use it:

Object sessionLock = MyHelper.getSessionLock(getRequest(), null);
synchronized (sessionLock) {
  ...
}

Any comments on this solution?

Solution 2

I found this nice explanation in JavaDoc for WebUtils.getSessionMutex():

In many cases, the HttpSession reference itself is a safe mutex as well, since it will always be the same object reference for the same active logical session. However, this is not guaranteed across different servlet containers; the only 100% safe way is a session mutex.

This method is used as a lock when synchronizeOnSession flag is set:

Object mutex = WebUtils.getSessionMutex(session);
synchronized (mutex) {
    return handleRequestInternal(request, response);
}

If you look at the implementation of getSessionMutex(), it actually uses some custom session attribute if present (under org.springframework.web.util.WebUtils.MUTEX key) or HttpSession instance if not:

Object mutex = session.getAttribute(SESSION_MUTEX_ATTRIBUTE);
if (mutex == null) {
    mutex = session;
}
return mutex;

Back to plain servlet spec - to be 100% sure use custom session attribute rather than HttpSession object itself.

See also

Solution 3

In general, don't rely on HttpServletRequest.getSession() returning same object. It's easy for servlet filters to create a wrapper around session for whatever reason. Your code will only see this wrapper, and it will be different object on each request. Put some shared lock into the session itself. (Too bad there is no putIfAbsent though).

Solution 4

As people already said, sessions can be wrapped by the servlet containers and this generates a problem: the session hashCode() is different between requests, i.e., they are not the same instance and thus can't be synchronized! Many containers allow persist a session. In this cases, in certain time, when session was expired, it is persisted on disk. Even when session is retrieved by deserialization, it is not same object as earlier, because it don't shares same memory address like when was at memory before the serialization process. When session is loaded from disk, it is put into memory for further access, until "maxInactiveInterval" is reached (expires). Summing up: the session could be not the same between many web requests! It will be the same while is in memory. Even if you put an attribute into the session to share lock, it will not work, because it will be serialized as well in the persistence phase.

Solution 5

Synchronization occurs when a lock is placed on an object reference, so that threads that reference the same object will treat any synchronization on that shared object as a toll gate.

So, what your question raises an interesting point: Does the HttpSession object in two separate web calls from the same session end up as the same object reference in the web container, or are they two objects that just happen to have similar data in them? I found this interesting discussion on stateful web apps which discusses HttpSession somewhat. Also, there is this discussion at CodeRanch about thread safety in HttpSession.

From those discussions, it seems like the HttpSession is indeed the same object. One easy test would be to write a simple servlet, look at the HttpServletRequest.getSession(), and see if it references the same session object on multiple calls. If it does, then I think your theory is sound and you could use it to sync between user calls.

Share:
19,713
basZero
Author by

basZero

WORK: Web App Developer, Java Enthusiast since 1995 HOME: I'm in love with photography

Updated on June 13, 2022

Comments

  • basZero
    basZero almost 2 years

    UPDATE: Solution right after question.

    Question:

    Usually, synchronization is serializing parallel requests within a JVM, e.g.

    private static final Object LOCK = new Object();
    
    public void doSomething() {
      ...
      synchronized(LOCK) {
        ...
      }
      ...
    }
    

    When looking at web applications, some synchronization on "JVM global" scope is maybe becoming a performance bottleneck and synchronization only within the scope of the user's HttpSession would make more sense.

    Is the following code a possibility? I doubt that synchronizing on the session object is a good idea but it would be interesting to hear your thoughts.

    HttpSession session = getHttpServletRequest().getSession();
    synchronized (session) {
      ...
    }
    

    Key Question:
    Is it guaranteed that the session object is the same instance for all threads processing requests from the same user?

    Summarized answer / solution:

    It seems that the session object itself is not always the same as it depends on the implementation of the servlet container (Tomcat, Glassfish, ...) and the getSession() method might return just a wrapper instance.

    So it is recommended to use a custom variable stored in the session to be used as locking object.

    Here is my code proposal, feedback is welcome:

    somewhere in a Helper Class, e.g. MyHelper:

    private static final Object LOCK = new Object();
    
    public static Object getSessionLock(HttpServletRequest request, String lockName) {
        if (lockName == null) lockName = "SESSION_LOCK";
        Object result = request.getSession().getAttribute(lockName);
        if (result == null) {
            // only if there is no session-lock object in the session we apply the global lock
            synchronized (LOCK) {
                // as it can be that another thread has updated the session-lock object in the meantime, we have to read it again from the session and create it only if it is not there yet!
                result = request.getSession().getAttribute(lockName);
                if (result == null) {
                    result = new Object();
                    request.getSession().setAttribute(lockName, result);
                }
            }
        }
        return result;
    }
    

    and then you can use it:

    Object sessionLock = MyHelper.getSessionLock(getRequest(), null);
    synchronized (sessionLock) {
      ...
    }
    

    Any comments on this solution?

  • basZero
    basZero about 12 years
    Thanks a lot for the first pointer, the author Brian Goetz is anyway the Guru when it comes to concurrency. As of his writing, it seems to be OK to synchronize on the session object: Serializing requests on an HttpSession makes many concurrency hazards go away
  • Peter Štibraný
    Peter Štibraný about 12 years
    If you do synchronization inside filter, then you're essentially disabling concurrent request processing for same session. It may or may not be what you want, but it sounds like too broad synchronization to me. One should always strive to synchronize on smallest possible area.
  • basZero
    basZero about 12 years
    Thanks for pointing out not to create useless session objects. The section where I would synchronize on the session is only within one specific usecase where the user is anyway logged in.
  • basZero
    basZero about 12 years
    Very good point regarding wrappers. The idea to put an object into the session is very good. Did you use that already?
  • Peter Štibraný
    Peter Štibraný about 12 years
    I've used combined technique ... lock object stored in the session, and synchronizing on the session itself for putting this lock object into it :-)
  • basZero
    basZero about 12 years
    Hi @PeterŠtibraný , something like in my summarized answer above?
  • Tomasz Nurkiewicz
    Tomasz Nurkiewicz about 12 years
    @basZero: no, I have shown code samples from Spring MVC source just to give you an example how it is implemented in mature web framework. You can base your own solution on these simple concepts.
  • basZero
    basZero about 12 years
    @Tomasz_Nurkiewicz ok, updated my question with a custom solution proposal.
  • Peter Štibraný
    Peter Štibraný about 12 years
    @basZero: yes, your code is almost line-to-line identical to mine. I've done the synchronization block on the session itself, but your solution is better (exactly for the reason stated in my answer).
  • basZero
    basZero over 10 years
    So you are saying that my documented solution won't work? I thought synchronizing on an object in the session (attribute) will work.
  • basZero
    basZero over 10 years
    No not yet, I'm in the process of finding the correct solution before I start implementation
  • basZero
    basZero over 10 years
    Thanks for your reply, but have a look at my summarized solution at the top. The object LOCK is only used when the session attributed is created, this is required to synchronize globally in order to avoid to requests creating objects in the session.
  • Mladen Adamovic
    Mladen Adamovic over 10 years
    I got deadlocks at my webapp numbeo.com when trying to synchronize globally when the session attribute is created. The underlying reason might be that some request, session and response methods might require round trip time which could go up to 1s max latency time.
  • basZero
    basZero over 10 years
    synchronizing globally is a valid use case. your deadlocks might come from your implementation, how you use them.
  • Mladen Adamovic
    Mladen Adamovic over 10 years
    are you sure that request, response and session method invoke after all request has been read in your web server (so it is cached in the container). If so, than you are right.
  • basZero
    basZero over 8 years
    interesting idea, however this serializes ALL requests of a user whereas my proposed solution can handle different user specific locks so that it is up to you to decide on serialization of user reqeusts.
  • daiscog
    daiscog over 8 years
    There are two problems, though: 1. The Servlet spec doesn't say that the return value of getSession should always be the same object. 2. If you have a filter (from a 3rd party lib, or otherwise) which wraps the Request object, that might also wrap the return value of getSession with a new wrapper every time. In short, if there are no guarantees, it is not safe.
  • CodeChimp
    CodeChimp over 8 years
    Man, @daiscog, talk about a blast-from-the-past...this was from like 3yrs ago! Anyway, I agree with you point and would reprimand my younger self for not thinking of all sides of the issue.
  • Vsevolod Golovanov
    Vsevolod Golovanov over 5 years
    This omits an important moment: thread-safely creating the mutex itself. The best approach probably is to do it in a HttpSessionListener on a sessionCreated event.
  • Denis Kokorin
    Denis Kokorin over 5 years
    Never intern string with default String.intern(). Otherwise you will flood String internal map with your own values without any possibility to clean it. Create your own interner, or better use libraries like guava or others.
  • Denis Kokorin
    Denis Kokorin over 5 years
    Double check-lock in your implementation is wrong. One can not simply read without locks/synchronization data written with locks/synchronization. Check this please cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
  • Number945
    Number945 about 3 years
    @DenisKokorin That is no longer true with Java 7 and above. baeldung.com/java-string-pool#garbage-collection
  • morgwai
    morgwai over 2 years
    I couldn't find any reliable information if intern() is thread-safe if 2 separate ClassLoaders load String class (also not entirely sure if it is possible to happen for a java.lang class to be loaded by 2 separate ClassLoaders...)
  • morgwai
    morgwai over 2 years
    it seems to me this has similar issue as double-locking: you check if a reference to an object is null outside of synchronized block, so you may get false (non-null, that is), but the object may not be fully initialized yet due to race conditions and write reorderings by compiler/VM.
  • morgwai
    morgwai over 2 years
    as explained in other answers, sync on session is not safe due to possible wrappings
  • morgwai
    morgwai over 2 years
    the OP is about "serializing parallel requests within a JVM". There's no way a synchronized block has anything to do with synchronization across separate JVMs or machines. For this, a distributed consensus mechanism would need to be used.