Store a supplier in a delegate function to be computed once, and only again after time to live (ttl) has expired. @param The type of object supplied @param original The java.util.function.Supplier to memoize @param ttlNanos Time in nanoseconds to retain
(Supplier<T> original, long ttlNanos)
| 71 | * @return A memoized version of the supplier |
| 72 | */ |
| 73 | public static <T> Supplier<T> memoize(Supplier<T> original, long ttlNanos) { |
| 74 | // Adapted from Guava's ExpiringMemoizingSupplier |
| 75 | return new Supplier<T>() { |
| 76 | final Supplier<T> delegate = original; |
| 77 | volatile T value; // NOSONAR squid:S3077 |
| 78 | volatile long expirationNanos; |
| 79 | |
| 80 | @Override |
| 81 | public T get() { |
| 82 | long nanos = expirationNanos; |
| 83 | long now = System.nanoTime(); |
| 84 | if (nanos == 0 || (ttlNanos >= 0 && now - nanos >= 0)) { |
| 85 | synchronized (this) { |
| 86 | if (nanos == expirationNanos) { // recheck for lost race |
| 87 | T t = delegate.get(); |
| 88 | value = t; |
| 89 | nanos = now + ttlNanos; |
| 90 | expirationNanos = (nanos == 0) ? 1 : nanos; |
| 91 | return t; |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | return value; |
| 96 | } |
| 97 | }; |
| 98 | } |
| 99 | |
| 100 | /** |
| 101 | * Store a supplier in a delegate function to be computed only once. |
no outgoing calls