title: Handling many simultaneous AJAX requests with a struts2 action
body: <p>I've got a struts2 action that responds to an AJAX request by taking some request parameters, calling a remote service that returns XML data, then transforming the data via XSL and returning the resulting XHTML via a Stream Result.  The response is different depending on the given parameters.</p>
  
  <p>Here is the action class with a bunch of stuff taken out:</p>
  
  <pre><code>public class ServiceHandler extends ActionSupport {
      private ByteArrayInputStream inputStream;
  
      public String execute(){
  
          String response = "";
  
          // Get request parameters
          // Make a request to a remote server via an http connection
          // Transform result via XSL
  
          //uses dom4j for XML/XSL stuff
          //this should never be empty
          response = resultDoc.asXML();
  
          inputStream = new ByteArrayInputStream(response.getBytes()); 
          return "success";
      }
  
      public ByteArrayInputStream getInputStream(){
          return inputStream;
      }
  }
  </code></pre>
  
  <p>And here are the important struts.xml bits:</p>
  
  <pre><code>&lt;action name="sh" class="ServiceHandler"&gt;
      &lt;result name="success" type="stream"&gt;
          &lt;param name="contentType"&gt;text/html&lt;/param&gt;
          &lt;param name="contentDisposition"&gt;inline;filename="response.html"&lt;/param&gt;
          &lt;param name="bufferSize"&gt;1024&lt;/param&gt;
          &lt;param name="allowCaching"&gt;false&lt;/param&gt;
      &lt;/result&gt;
  &lt;/action&gt;
  </code></pre>
  
  <p>My problem is that when I have multiple requests going at the same time, all calling the ServiceHandler action, sometimes the response is totally blank (should never happen), sometimes the response is cut off at the beginning or end by some random amount, and sometimes the responses are switched, so that the wrong response is received by a an AJAX requestor.</p>
  
  <p>I know this is an issue of thread safety, and I've moved all important variable definitions into the execute() method so that they are not instance variables (and hence shared by all).  The only interesting variable that is an instance variable is the inputStream, and I'm looking at that as the cause of my problems.</p>
  
  <p>Is there a way to make the inputStream variable thread-safe?  Or is there another solution I'm not seeing?</p>