Richard Searle's Blog

Thoughts about software

Unusual java httpserver race condition

Posted by eggsearle on August 29, 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{
   public void handle(HttpExchange exchange) throws IOException {

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: