title: Is synchronization within an HttpSession feasible?
body: <p><strong>UPDATE:</strong> Solution right after question.</p>
  <h1><strong>Question:</strong></h1>
  <p>Usually, synchronization is serializing parallel requests within a JVM, e.g.</p>
  <pre><code>private static final Object LOCK = new Object();
  
  public void doSomething() {
    ...
    synchronized(LOCK) {
      ...
    }
    ...
  }
  </code></pre>
  <p>When looking at web applications, some synchronization on &quot;JVM global&quot; scope is maybe becoming a performance bottleneck and synchronization only within the scope of the user's <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpSession.html" rel="noreferrer">HttpSession</a> would make more sense.</p>
  <p>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.</p>
  <pre><code>HttpSession session = getHttpServletRequest().getSession();
  synchronized (session) {
    ...
  }
  </code></pre>
  <p><strong>Key Question:</strong><br />
  Is it guaranteed that the session object is <strong>the same instance</strong> for all threads processing requests from the same user?</p>
  <h1><strong>Summarized answer / solution:</strong></h1>
  <p>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 <code>getSession()</code> method might return just a wrapper instance.</p>
  <p><strong>So it is recommended to use a custom variable stored in the session to be used as locking object.</strong></p>
  <p>Here is my code proposal, feedback is welcome:</p>
  <p>somewhere in a Helper Class, e.g. <code>MyHelper</code>:</p>
  <pre><code>private static final Object LOCK = new Object();
  
  public static Object getSessionLock(HttpServletRequest request, String lockName) {
      if (lockName == null) lockName = &quot;SESSION_LOCK&quot;;
      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;
  }
  </code></pre>
  <p>and then you can use it:</p>
  <pre><code>Object sessionLock = MyHelper.getSessionLock(getRequest(), null);
  synchronized (sessionLock) {
    ...
  }
  </code></pre>
  <p>Any comments on this solution?</p>