net.intelie.pipes.util.ValueCache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pipes-api Show documentation
Show all versions of pipes-api Show documentation
Intelie Pipes' API classes and interfaces
package net.intelie.pipes.util;
public abstract class ValueCache {
private final long ttl;
private final T defaultValue;
private volatile T value;
private volatile long time = Long.MIN_VALUE;
public ValueCache(long ttl) {
this(ttl, null);
}
public ValueCache(long ttl, T defaultValue) {
this.ttl = ttl;
this.defaultValue = defaultValue;
}
public abstract T load() throws Exception;
public T get() {
long now = System.nanoTime();
if (checkTtl(now)) {
synchronized (this) {
if (checkTtl(now)) {
value = makeValue();
time = now;
}
}
}
return value;
}
private boolean checkTtl(long now) {
return now > time + ttl * 1000000;
}
private T makeValue() {
try {
return load();
} catch (Throwable e) {
return defaultValue;
}
}
}