[Change] CacheObject, LocalHashCacheStore 合并类;

This commit is contained in:
LamGC 2020-04-16 23:48:59 +08:00
parent d8d4784c0f
commit ac38e1b5cf
2 changed files with 42 additions and 40 deletions

View File

@ -1,40 +0,0 @@
package net.lamgc.cgj.bot.cache;
import java.util.Date;
import java.util.concurrent.atomic.AtomicReference;
public class CacheObject<T> {
private AtomicReference<T> value;
private AtomicReference<Date> expire;
public CacheObject() {
this(null, null);
}
public CacheObject(T value, Date expire) {
this.value = new AtomicReference<>(value);
this.expire = new AtomicReference<>(expire);
}
public synchronized void update(T value, Date newExpire) {
if(new Date().after(newExpire)) {
throw new IllegalArgumentException("Due earlier than current time");
}
this.expire.set(newExpire);
this.value.set(value);
}
public synchronized T get() {
return value.get();
}
public Date getExpireDate() {
return expire.get();
}
public boolean isExpire(Date time) {
Date expireDate = getExpireDate();
return expireDate != null && expireDate.before(time);
}
}

View File

@ -1,8 +1,11 @@
package net.lamgc.cgj.bot.cache; package net.lamgc.cgj.bot.cache;
import org.jetbrains.annotations.NotNull;
import java.util.Date; import java.util.Date;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
public class LocalHashCacheStore<T> implements CacheStore<T> { public class LocalHashCacheStore<T> implements CacheStore<T> {
@ -99,4 +102,43 @@ public class LocalHashCacheStore<T> implements CacheStore<T> {
public boolean supportedList() { public boolean supportedList() {
return false; return false;
} }
public static class CacheObject<T> implements Comparable<CacheObject<T>> {
private AtomicReference<T> value;
private AtomicReference<Date> expire;
public CacheObject(T value, Date expire) {
this.value = new AtomicReference<>(value);
this.expire = new AtomicReference<>(expire);
}
public synchronized void update(T value, Date newExpire) {
if(new Date().after(newExpire)) {
throw new IllegalArgumentException("Due earlier than current time");
}
this.expire.set(newExpire);
this.value.set(value);
}
public synchronized T get() {
return value.get();
}
public Date getExpireDate() {
return expire.get();
}
public boolean isExpire(Date time) {
Date expireDate = getExpireDate();
return expireDate != null && expireDate.before(time);
}
@Override
public int compareTo(@NotNull CacheObject<T> o) {
return this.getExpireDate().after(o.getExpireDate()) ? -1 : 1;
}
}
} }