Search code examples
scalaasynchronouscallbackdelay

Mock network delay asynchronously


I have a Scala application that relies on an external RESTful webservice for some part of its functionality. We'd like to do some performance tests on the application, so we stub out the webservice with an internal class that fakes the response.

One thing we would like to keep in order to make the performance test as realistic as possible is the network lag and response time from the remote host. This is between 50 and 500 msec (we measured).

Our first attempt was to simply do a Thread.sleep(random.nextInt(450) + 50), however I don't think that's accurate - we use NIO, which is non-blocking, and Thread.sleep is blocking and locks up the whole thread.

Is there a (relatively easy / short) way to stub a method that contacts an external resource, then returns and calls a callback object when ready? The bit of code we would like to replace with a stub implementation is as follows (using Sonatype's AsyncHttpClient), where we wrap its completion handler object in one of our own that does some processing:

def getActualTravelPlan(trip: Trip, completionHandler: AsyncRequestCompletionHandler) {
    val client = clientFactory.getHttpClient
    val handler = new TravelPlanCompletionHandler(completionHandler)
    // non-blocking call here.
    client.prepareGet(buildApiURL(trip)).setRealm(realm).execute(handler)
}

Our current implementation does a Thread.sleep in the method, but that's, like I said, blocking and thus wrong.


Solution

  • Use a ScheduledExecutorService. It will allow you to schedule things to run at some time in the future. Executors has factory methods for creating them fairly simply.