summaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/time/TimeBudget.java
blob: fe2657585bc929dbc30d7d13009cc429cddd4bed (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.time;

import java.time.Clock;
import java.time.Duration;
import java.time.Instant;

/**
 * A TimeBudget can be used to track the time of an ongoing operation with a timeout.
 *
 * @author hakon
 */
public class TimeBudget {
    private final Clock clock;
    private final Instant start;
    private final Duration timeout;

    /** Returns a TimeBudget with a start time of now, and with the given timeout. */
    public static TimeBudget fromNow(Clock clock, Duration timeout) {
        return new TimeBudget(clock, clock.instant(), timeout);
    }

    private TimeBudget(Clock clock, Instant start, Duration timeout) {
        this.clock = clock;
        this.start = start;
        this.timeout = makeNonNegative(timeout);
    }

    /** Returns time since start. */
    public Duration timePassed() {
        return nonNegativeBetween(start, clock.instant());
    }

    /** Returns the original timeout. */
    public Duration originalTimeout() {
        return timeout;
    }

    /**
     * Returns the time until deadline.
     *
     * @return time until deadline. It's toMillis() is guaranteed to be positive.
     * @throws TimeoutException if the deadline has been reached or passed.
     */
    public Duration timeLeftOrThrow() {
        Instant now = clock.instant();
        Duration left = Duration.between(now, start.plus(timeout));
        if (left.toMillis() <= 0) {
            throw new TimeoutException("Time since start " + nonNegativeBetween(start, now) +
                    " exceeds timeout " + timeout);
        }

        return left;
    }

    private static Duration nonNegativeBetween(Instant start, Instant end) {
        return makeNonNegative(Duration.between(start, end));
    }

    private static Duration makeNonNegative(Duration duration) {
        return duration.isNegative() ? Duration.ZERO : duration;
    }
}