A Glimpse of Awaitility

Today I had a task to first deploy a webapp and then verify whether it was properly deployed. Obviously there are things to consider:

  • it takes time till the app is deployed and started,
  • it is hard to say how long it takes.

One solution would be to wait for some safe time (2 minutes? 3 minutes?) and then check if the app responds to requests. Yes, but it would be definitely more efficient to do it in some kind of a loop, so you do not waste too much time if, for example, everything is up and ready in 1 minute 20 seconds.

So at first I write my own while loop with some Thread.sleep() calls, but then I thought about using Awaitility for this.

Awaitility is "a small Java-based DSL for synchronizing asynchronous operations. It makes it easy to test asynchronous code." Even if testing is its primary goal, it also fits perfectly to my problem.

This is roughly what I ended up with (you can fetch the code from github):

import java.util.concurrent.Callable;

import static com.jayway.awaitility.Awaitility.with;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;

@Test
public class AwaitilityServerExample {

    public void verifyAppIsStarted() throws Exception {
        with().pollDelay(1, MINUTES)
              .and().with().pollInterval(5, SECONDS)
              .await("waiting for web app to be ready")
              .atMost(3, MINUTES)
              .until(webAppResponds());
    }

    private Callable<Boolean> webAppResponds() {
        return new Callable<Boolean>() {
            public Boolean call() throws Exception {
                boolean result = ... // here calling some servlets to
                                     //determine if the web app works
                return result;
            }
        };
    }
}
As you can see the DSL is quite readable, and it takes all the burden of loop writing and waiting. There are some more goodies there, so make sure you read Awaitility's documentation.

 
 
 
This used to be my blog. I moved to http://tomek.kaczanowscy.pl long time ago.

 
 
 

Please comment using