title: Portlets, HttpSession and Thread-Safety
body: <p>Our portlets keep state in the HttpSession, which is shared by all request processing threads for the same session.</p>
  
  <p>The portlet spec (JSR-168) writes:</p>
  
  <blockquote>
    <p><strong>PLT.5.2.4.3 Multithreading Issues During Request Handling</strong></p>
    
    <p>The portlet container handles concurrent requests to the same portlet by concurrent
    execution of the request handling methods on different threads. Portlet developers must
    design their portlets to handle concurrent execution from multiple threads from within the
    <code>processAction</code> and <code>render</code> methods at any particular time.</p>
  </blockquote>
  
  <p>I wonder how I am supposed to achieve that? Sure, I can use synchronization to achieve mutual exclusion during both <code>processAction</code> and <code>render</code>, but I don't see how I can enforce atomicity of request processing as a whole. In particular, I worry about the following scenario:</p>
  
  <ul>
  <li>Thread 1 executes <code>processAction</code>, loading data into the session for later rendering</li>
  <li>Thread 2 executes <code>processAction</code>, discarding that data from the session</li>
  <li>Thread 1 executes <code>render</code>, reading the data to render from the session, and throws a NullPointerException because the prepared data is no longer there ...</li>
  </ul>
  
  <p>How is that scenario usually prevented? In particular, when using the JBoss portlet bridge to adapt JSF to a Portlet environment?</p>