blob: c50f5e6c2d5478303d4fd3105d0ad4ac4fde8b93 (
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
64
65
66
67
68
69
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.service.model;
import com.yahoo.jdisc.Timer;
import com.yahoo.vespa.service.monitor.ServiceModel;
import java.util.function.Supplier;
/**
* Adds caching of a supplier of ServiceModel.
*
* @author hakonhall
*/
public class ServiceModelCache implements Supplier<ServiceModel> {
public static final long EXPIRY_MILLIS = 10000;
private final Supplier<ServiceModel> expensiveSupplier;
private final Timer timer;
private volatile ServiceModel snapshot;
private boolean updatePossiblyInProgress = false;
private final Object updateMonitor = new Object();
private long snapshotMillis;
public ServiceModelCache(Supplier<ServiceModel> expensiveSupplier, Timer timer) {
this.expensiveSupplier = expensiveSupplier;
this.timer = timer;
}
@Override
public ServiceModel get() {
if (snapshot == null) {
synchronized (updateMonitor) {
if (snapshot == null) {
takeSnapshot();
}
}
} else if (expired()) {
synchronized (updateMonitor) {
if (updatePossiblyInProgress) {
return snapshot;
}
updatePossiblyInProgress = true;
}
try {
takeSnapshot();
} finally {
synchronized (updateMonitor) {
updatePossiblyInProgress = false;
}
}
}
return snapshot;
}
private void takeSnapshot() {
snapshot = expensiveSupplier.get();
snapshotMillis = timer.currentTimeMillis();
}
private boolean expired() {
return timer.currentTimeMillis() - snapshotMillis >= EXPIRY_MILLIS;
}
}
|