001/*
002 * PermissionsEx
003 * Copyright (C) zml and PermissionsEx contributors
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *    http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package ca.stellardrift.permissionsex.impl.util;
018
019import java.util.function.LongSupplier;
020import java.util.function.Supplier;
021
022import static java.util.Objects.requireNonNull;
023
024public final class CachingValue<V> {
025    private final LongSupplier currentTime;
026    private final long maxDelta;
027    private final Supplier<V> updater;
028    private volatile long lastTime;
029    private volatile V lastValue;
030
031    /**
032     * Create a value that is cached for a certain amount of time.
033     */
034    public static <V> CachingValue<V> timeBased(final long maxDelta, final Supplier<V> updateFunc) {
035        return new CachingValue<>(System::currentTimeMillis, maxDelta, updateFunc);
036    }
037
038    public CachingValue(final LongSupplier currentTime, final long maxDelta, final Supplier<V> updater) {
039        requireNonNull(currentTime, "currentTime");
040        requireNonNull(updater, "updater");
041        this.currentTime = currentTime;
042        this.maxDelta = maxDelta;
043        this.updater = updater;
044        this.refresh();
045    }
046
047    public V get() {
048        final long now = currentTime.getAsLong();
049        if ((now - this.lastTime) > this.maxDelta) {
050            this.lastValue = updater.get();
051            this.lastTime = now;
052        }
053        return this.lastValue;
054    }
055
056    public void refresh() {
057        this.lastValue = this.updater.get();
058        this.lastTime = currentTime.getAsLong();
059    }
060}