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

com.swak.license.core.Cache Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (C) 2005 - 2019 Schlichtherle IT Services.
 * All rights reserved. Use is subject to license terms.
 */
package com.swak.license.core;

import java.util.Optional;

import static java.lang.System.currentTimeMillis;

/**
 * A simple time sensitive cache with just one association.
 * This class is immutable.
 */
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
final class Cache {

    private final Optional optKey;
    private final Optional optValue;
    private final long cachePeriodMillis, startTimeMillis = currentTimeMillis();

    Cache() { this(Optional.empty(), Optional.empty(), 0); } // => obsolete() == true

    Cache(final Optional optKey, final Optional optValue, final long cachePeriodMillis) {
        this.optKey = optKey;
        this.optValue = optValue;
        if (0 > (this.cachePeriodMillis = cachePeriodMillis)) {
            throw new IllegalArgumentException();
        }
    }

    Cache key(Optional optKey) {
        return hasKey(optKey) ? this : new Cache<>(optKey, optValue, cachePeriodMillis);
    }

    Optional map(Optional optKey) {
        return hasKey(optKey) && !obsolete() ? optValue : Optional.empty();
    }

    boolean hasKey(Optional optKey) { return optKey.equals(this.optKey); }

    boolean obsolete() { return currentTimeMillis() - startTimeMillis >= cachePeriodMillis; }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy