aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/lang/CachedSupplier.java
blob: ad09ac6b4a8e706937bf42cad41a4f536c17e071 (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 Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.lang;

import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.function.Supplier;

/**
 * Supplier that caches the value for a given duration with ability to invalidate on demand.
 * Is thread safe.
 *
 * @author freva
 */
public class CachedSupplier<T> implements Supplier<T> {

    private final Object monitor = new Object();

    private final Supplier<T> delegate;
    private final Duration period;
    private final Clock clock;

    private Instant nextRefresh;
    private volatile T value;

    public CachedSupplier(Supplier<T> delegate, Duration period) {
        this(delegate, period, Clock.systemUTC());
    }

    CachedSupplier(Supplier<T> delegate, Duration period, Clock clock) {
        this.delegate = delegate;
        this.period = period;
        this.clock = clock;
        this.nextRefresh = Instant.MIN;
    }

    @Override
    public T get() {
        synchronized (monitor) {
            if (clock.instant().isAfter(nextRefresh)) {
                this.value = delegate.get();
                this.nextRefresh = clock.instant().plus(period);
            }
        }

        return value;
    }

    public void invalidate() {
        synchronized (monitor) {
            this.nextRefresh = Instant.MIN;
        }
    }

}