Files
CustomNPC-Plus/src/main/java/noppes/npcs/util/CacheHashMap.java
T

78 lines
2.2 KiB
Java
Raw Normal View History

2023-05-30 23:41:37 -05:00
package noppes.npcs.util;
2024-02-15 17:54:28 -05:00
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
2023-05-30 23:41:37 -05:00
public class CacheHashMap<K, V extends CacheHashMap.CachedObject<?>> extends HashMap<K, V> {
private final long maxCacheTime;
private long saveInterval;
2023-05-30 23:41:37 -05:00
public CacheHashMap(long maxCacheTime) {
this.maxCacheTime = maxCacheTime;
}
public CacheHashMap(long maxCacheTime, long saveInterval) {
this.maxCacheTime = maxCacheTime;
this.saveInterval = saveInterval;
}
2023-05-30 23:41:37 -05:00
@Override
public V get(Object key) {
V object = super.get(key);
object.updateTimeAccessed();
2025-03-12 20:12:01 -04:00
Iterator<Map.Entry<K, V>> iterator = this.entrySet().iterator();
while (iterator.hasNext()) {
2025-03-12 20:12:01 -04:00
Map.Entry<K, V> entry = iterator.next();
long lifeTimeDiff = entry.getValue().timeSinceAccessed();
if (lifeTimeDiff > this.maxCacheTime) {
entry.getValue().save();
iterator.remove();
} else if (this.saveInterval > 0) {
long saveTimeDiff = entry.getValue().timeSinceSaved();
if (saveTimeDiff > this.saveInterval) {
entry.getValue().save();
entry.getValue().updateSaveTime();
}
}
}
2023-05-30 23:41:37 -05:00
return object;
}
public static class CachedObject<T> {
private long timeSaved;
2023-05-30 23:41:37 -05:00
private long lastTimeAccessed;
private final T object;
public CachedObject(T object) {
this.object = object;
this.lastTimeAccessed = System.currentTimeMillis();
this.timeSaved = System.currentTimeMillis();
2023-05-30 23:41:37 -05:00
}
public long timeSinceAccessed() {
return System.currentTimeMillis() - this.lastTimeAccessed;
}
public long timeSinceSaved() {
return System.currentTimeMillis() - this.timeSaved;
}
2023-05-30 23:41:37 -05:00
public void updateTimeAccessed() {
this.lastTimeAccessed = System.currentTimeMillis();
}
public void updateSaveTime() {
this.timeSaved = System.currentTimeMillis();
}
2025-03-12 20:12:01 -04:00
public void save() {
}
2023-05-30 23:41:37 -05:00
public T getObject() {
return this.object;
}
}
}