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

org.opentripplanner.common.model.CachedValue Maven / Gradle / Ivy

There is a newer version: 2.6.0
Show newest version
package org.opentripplanner.common.model;

import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
import java.util.function.Supplier;
import javax.annotation.Nonnull;

/**
 * The purpose of this class is to be a generic container for caching expensive computations.
 * 

* THIS CLASS IS THREAD-SAFE. */ public class CachedValue { private final Duration cacheInterval; private T value; private Instant timeout; public CachedValue(@Nonnull Duration cacheInterval) { this.value = null; this.cacheInterval = cacheInterval; this.timeout = calculateTimeout(); } /** * If the cached value has not expired, then return it. *

* Otherwise, recompute and return it. */ public T get(@Nonnull Supplier supplier) { synchronized (this) { if (hasExpired()) { this.value = supplier.get(); this.timeout = calculateTimeout(); } } return value; } private Instant calculateTimeout() { return Instant.now().plus(cacheInterval); } private boolean hasExpired() { return value == null || timeout.isBefore(Instant.now()); } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy