Over a million developers have joined DZone.

Ratpacked: Get Time Taken to Fulfill a Promise [Snippet]

DZone's Guide to

Ratpacked: Get Time Taken to Fulfill a Promise [Snippet]

Ratpack's time method is useful for tracking the time it takes for Promise results to become available. See how to measure durations in your projects.

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

The Promise class has a lot of methods. One of the methods is the time method. We can invoke this method in a Promise instance. The method creates a Duration object that we can use inside the method. The duration is the time taken from when the promise is subscribed to when the result is available. The promise value is not changed, so we can add the time method at any position of a method chain for the Promise object.

In the following specification, we check the duration for a Promise that is returned by the method generate of the class Numbers. For our example, we wait for a number of seconds dependent on the argument of the generate method. In the specification, we use the time method and check the time spent to fulfill the promise.

package mrhaki.ratpack
import ratpack.exec.Promise
import ratpack.test.exec.ExecHarness
import spock.lang.Specification
import spock.lang.Unroll
import java.time.Duration
class NumbersSpec extends Specification {
    @Unroll('with argument #num response time should be at least #responseTime')
    void 'time used by Numbers.generate method increased and dependent on argument'() {
        final numbers = new Numbers()
        long timer
        final result = ExecHarness.yieldSingle {
                   .map { value -> value - 1 }
                   .time { duration -> timer = duration.toMillis() }
        timer >= responseTime
        result.value == generateResult
        num | responseTime | generateResult
        1   | 1_000        | 0
        2   | 2_000        | 3
        10  | 10_000       | 99
class Numbers  {
    Promise<Long> generate(final Long multiplier) {
            .sync { ->
                 // Wait for n-seconds...
                 sleep(multiplier * 1000)
            .map { value ->
                value * value

Written with Ratpack 1.4.5.

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

ratpack ,java ,promises

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}