2

I'm getting some strange results sending multiple asynchronous AJAX calls to the same java servlet at the roughly the same time.

For example, let's say I send off two AJAX requests at the same time using jQuery.

//ajax call foo
$.post('LookupServlet', {
  method: 'findFoo'
};

//ajax call bar
$.post('LookupServlet', {
  method: 'findBar'
};

In my servlet it invokes the given method. The method writes a response to the stream.

What is strange is that that foo sometimes gets the response for bar. And vice versa. Or sometimes one ajax call is getting both responses. Or one request gets a response and the other one doesn't.

I've never seen anything quite like this before in other server-side languages, I didn't even know it was possible. Does anyone have any theories as to why this is happening? How do Java servlets operate where simultaneous requests could get crossed responses?

John Strickler
  • 23,772
  • 4
  • 49
  • 67

1 Answers1

3

The likely cause is that the servlets are not written to be thread safe. Note that the object that contains the servlet methods may be used to respond to many simultaneous requests. If that method uses a class level variable to create the response, then requests will appear to get 'mixed up'.

So.. Request #1 comes in, is assigned to an instance of Servlet, Instance #1

The appropriate method is invoked on Instance #1, which starts using a class variable to calculate the result. Instance #1.myVariable = "Blah"

Now, Request #2 comes in, is also assigned to Instance #1

Again, the appropriate method is invoked on Instance #1, which sets Instance #1.myVariable ="Foo"

.. in the mean time the first request completes, and returns Instance #1.myVariable... "Foo"!

.. and then the second request completes, and also returns "Foo".

AndyT
  • 1,293
  • 7
  • 11
  • Thank you for the high-level explanation. That's what I was looking for... and I am using a class level variable to send the response! – John Strickler Apr 07 '11 at 16:37
  • Follow-up, I changed the PrintWriter from a class variable to a local variable and all is well. Thanks again. – John Strickler Apr 07 '11 at 16:44
  • Perhaps this is the answer of my question here http://stackoverflow.com/questions/38971527/jquery-ajax-sucess-response-parameter-overwriting?noredirect=1#comment65297742_38971527 – techie_28 Aug 16 '16 at 10:59
  • I dont know about servlets but I am aware they are using JAVA as backend language. – techie_28 Aug 16 '16 at 11:01