mirror of
https://github.com/KAMKEEL/CustomNPC-Plus.git
synced 2026-11-17 09:55:11 +00:00
CacheHashMap:
-New class extending from the HashMap class, only takes CacheHashMap.CachedObject as values, which itself is a template class. -On every call to get(), it goes through its values and removes any that are past a set age in millis. ClientCache: -New class with static CacheHashMap and function to get image data, will do more caching later on.
This commit is contained in:
1 parent
ab8e966f71
commit
46febe5c0a
6 files changed
+83
-17
No files matched your search
@@ -0,0 +1,56 @@
|
||||
package noppes.npcs.util;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class CacheHashMap<K, V extends CacheHashMap.CachedObject<?>> extends HashMap<K, V> {
|
||||
private final long maxCacheTime;
|
||||
|
||||
public CacheHashMap(long maxCacheTime) {
|
||||
this.maxCacheTime = maxCacheTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public V get(Object key) {
|
||||
synchronized (this) {
|
||||
List<K> keysToRemove = new ArrayList<>();
|
||||
for (Map.Entry<K,V> entry : this.entrySet()) {
|
||||
if (!Objects.equals(key,entry.getKey())) {
|
||||
long timeDiff = entry.getValue().timeSinceAccessed();
|
||||
if (timeDiff > this.maxCacheTime) {
|
||||
keysToRemove.add(entry.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (K k : keysToRemove) {
|
||||
this.remove(k);
|
||||
}
|
||||
}
|
||||
|
||||
V object = super.get(key);
|
||||
object.updateTimeAccessed();
|
||||
|
||||
return object;
|
||||
}
|
||||
|
||||
public static class CachedObject<T> {
|
||||
private long lastTimeAccessed;
|
||||
private final T object;
|
||||
|
||||
public CachedObject(T object) {
|
||||
this.object = object;
|
||||
this.lastTimeAccessed = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public long timeSinceAccessed() {
|
||||
return System.currentTimeMillis() - this.lastTimeAccessed;
|
||||
}
|
||||
|
||||
public void updateTimeAccessed() {
|
||||
this.lastTimeAccessed = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public T getObject() {
|
||||
return this.object;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user