in concurrency-loadbalancer-core/src/main/java/com/uber/concurrency/loadbalancer/timedcounter/LifespanTracker.java [74:109]
public long add(long n, Duration timeToLive) {
if (maxAge.minus(timeToLive).isNegative()) {
timeToLive = maxAge;
}
if (timeToLive.isNegative()) {
timeToLive = Duration.ZERO;
}
long nowNanos = ticker.read();
if (windowNanos == 0) {
toBePurged.addAndGet(n);
return nowNanos;
}
long windowId = (nowNanos + timeToLive.toNanos()) / windowNanos;
long windowUpperNano = (windowId + 1) * windowNanos;
//windowId could be negative
int index = (int) (((windowId % totalWindows) + totalWindows) % totalWindows);
Window window = windows[index];
if (window.windowId < windowId) {
synchronized (window) {
if (window.windowId < windowId) {
toBePurged.addAndGet(window.count.getAndSet(n));
window.windowId = windowId;
return windowUpperNano;
}
}
}
if (window.windowId > windowId) {
toBePurged.addAndGet(n);
} else {
window.count.addAndGet(n);
}
return windowUpperNano;
}