Richard Searle

home

Unusual java httpserver race condition

29 Aug 2012

The JDK httpserver provides a simple implementation that can easily be applied to unit tests. The following example would generate a response containing responseBytes. It might be expected that the referencing code would only see the response when exchange.close() is called. In reality, the response can be seen as soon as the write executes! That does not matter in a real web server since the client cannot be aware of the internal processing of the server. Unit tests intrinsically couple the client and server together so as to progress through the test steps and validate the state of both parties. This race condition caused unit tests to randomly fail, which is always hard to diagnose.
private static class MockHandler implements HttpHandler{
   @Override
   public void handle(HttpExchange exchange) throws IOException {
       exchange.getResponseBody().write(responseBytes);
       exchange.close();
   }
}