com.swak.license.core.Cache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of swak-license-core Show documentation
Show all versions of swak-license-core Show documentation
swak component of trueLicense core
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; }
}