The waiting is the hardest part

I've been using a utility for some time now that has been absolutely awesome to work with but I don't think it's gotten enough attention.  For those who haven't yet heard of it, let me introduce you to one my favorite utilities: Awaitility.​  

Awaitility_logo_red_small.png

This little utility does one thing really, really well.​  Using its simple API, you can defer execution of a method to a thread and wait for it to finish or time out.  Let's look at some examples to see how this works.  The most obvious example is probably waiting for network IO to finish.  We don't want to wait forever for something to download.  Using Awaitility, it'd look something like this:

Awaitility.await().atMost(new Duration(10, TimeUnit.MINUTES))
.until(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return file.exists();
}
});

In this example, we'll wait at most 10 minutes for the file to download.  Awaitility will call your Callable every so often until call() returns true.  The default polling time is 100ms but this configurable by calling pollInterval() in your method chain.  You can also choose to wait a certain duration before polling begin via pollDelay().

If you just need to run some method, however, that doesn't really return anything or you don't care about the return value, you can simply make that blocking call in your Callable like so:

Awaitility.await().atMost(new Duration(10, TimeUnit.MINUTES))
.until(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
blockingCall();
return true;
}
});

For as much as it lets you do, Awaitility has very simple API.  If scala or groovy is your preferred language, there are bindings for those as well, though I've no experience with those versions.​