All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.intelie.pipes.util.ValueCache Maven / Gradle / Ivy

There is a newer version: 0.25.5
Show newest version
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;
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy