Fix expiration time check in ExpirationMap
Add helper methods for checking past and future timestamp
Co-authored-by: Kristijan Mitrovic <kmitrovic@itekako.com>
Reviewed-on: https://git.bubblev.org/bubblev/cobbzilla-utils/pulls/2
if (lastCleaned+cleanInterval > now()) cleanExpired();
if (isTimestampInPast(nextCleaningTime)) cleanExpired();
final ExpirationMapEntry<V> val = map.putIfAbsent(key, new ExpirationMapEntry<>(value));
return val == null ? null : val.value;
}
@Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
if (lastCleaned+cleanInterval > now()) cleanExpired();
if (isTimestampInPast(nextCleaningTime)) cleanExpired();
return map.computeIfAbsent(key, k -> new ExpirationMapEntry<>(mappingFunction.apply(k))).value;
}
@Override public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
if (lastCleaned+cleanInterval > now()) cleanExpired();
if (isTimestampInPast(nextCleaningTime)) cleanExpired();
final ExpirationMapEntry<V> found = map.computeIfPresent(key, (k, vExpirationMapEntry) -> new ExpirationMapEntry<>(remappingFunction.apply(k, vExpirationMapEntry.value)));
return found == null ? null : found.value;
}
@@ -135,12 +158,13 @@ public class ExpirationMap<K, V> implements Map<K, V> {
}
@Override public Set<Entry<K, V>> entrySet() {
if (isTimestampInPast(nextCleaningTime)) cleanExpired();
return map.entrySet().stream().map(e -> new EMEntry<>(e.getKey(), e.getValue().value)).collect(Collectors.toSet());
}
private synchronized void cleanExpired () {
if (lastCleaned+cleanInterval < now()) return;
lastCleaned = now();
if (isTimestampInFuture(nextCleaningTime)) return;
nextCleaningTime = now() + cleanInterval;
final Set<K> toRemove = new HashSet<>();
for (Map.Entry<K, ExpirationMapEntry<V>> entry : map.entrySet()) {
if (entry.getValue().expired()) toRemove.add(entry.getKey());
+ 2- 0
src/main/java/org/cobbzilla/util/time/TimeUtil.javaZobrazit soubor
@@ -223,4 +223,6 @@ public class TimeUtil {
return new DateTime(zone).withTimeAtStartOfDay().withFieldAdded(DurationFieldType.years(), -1).withDayOfYear(1);
}
public static boolean isTimestampInFuture(long t) { return t > now(); }
public static boolean isTimestampInPast(long t) { return t < now(); }
}
+ 40- 0
src/test/java/org/cobbzilla/util/collection/ExpirationMapTest.javaZobrazit soubor