summaryrefslogtreecommitdiffstats
path: root/jdisc_core/src/main/java/com/yahoo/jdisc/TimeBudget.java
blob: 39322b6e83a04c6186e6e4faad6d77141286a207 (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
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc;

import javax.annotation.concurrent.Immutable;
import java.time.Duration;
import java.time.Instant;

/**
 * A TimeBudget tracks the current time compared to a start time and deadline.
 *
 * @author hakon
 */
@Immutable
public class TimeBudget {
    private final Timer timer;
    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(Timer timer, Duration timeout) {
        return new TimeBudget(timer, timer.currentTime(), timeout);
    }

    private TimeBudget(Timer timer, Instant start, Duration timeout) {
        this.timer = timer;
        this.start = start;
        this.timeout = timeout;
    }

    /** Time until 'headroom' before deadline. Guaranteed to be non-negative. */
    public Duration timeBeforeDeadline(Duration headroom) {
        return nonNegativeBetween(now(), deadline().minus(headroom));
    }

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

    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;
    }

    private Instant now() {
        return timer.currentTime();
    }

    private Instant deadline() {
        return start.plus(timeout);
    }
}