I’ve got two servlets, as follows:
public class ServletA extends HttpServlet {
public void doGet(final HttpServletRequest request,
final HttpServletResponse response) {
// Kick off some async processing
RequestQueue.putRequest(new RequestInfo(...), new FutureCallback<ResponseInfo> () {
@Override
public void completed(ResponseInfo responseInfo) {
// Send some data to database
TransactionManager.getInstance().create(...);
}
)};
// Send response to client
response.getWriter().println("ServletA: SUCCESS");
}
}
public class ServletB extends HttpServlet {
public void doGet(final HttpServletRequest request,
final HttpServletResponse response) {
// Use a CountDownLatch to force synchronous processing on an asynchronous construct
final CountDownLatch completedSignal = new CountDownLatch(1);
RequestQueue.putRequest(new RequestInfo(...), new FutureCallback<ResponseInfo> () {
@Override
public void completed(ResponseInfo responseInfo) {
// Send some data to database, and send response to client
TransactionManager.getInstance().create(...);
response.getWriter().println("ServletB: SUCCESS");
completedSignal.countDown();
}
)};
completedSignal.await();
}
}
The problem is, under heavy load, a client that makes a call to ServletA will sometimes receive “Servlet B: SUCCESS” as a response.
Why should this be? How might it be fixed?
Thanks.
Adding an AtomicBoolean to ServletB to ensure that the response object was only used once fixed the problem: