1 回答

TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
如果您使用的是桌面設(shè)備,您可以查看 Google Guava,它有許多緩存實(shí)用程序,包括創(chuàng)建具有逐出時(shí)間的條目的功能。使用它,您可以添加條目并驅(qū)逐 10 分鐘。然后,當(dāng)新的 JSON 進(jìn)來時(shí),您可以檢查它是否存在于緩存中。如果不是,則發(fā)送通知,如果是,則重新設(shè)置驅(qū)逐時(shí)間。
您也可以編寫自己的 EvictionMap。擴(kuò)展ConcurrentHashMap,并在構(gòu)造函數(shù)中創(chuàng)建一個(gè)線程并啟動(dòng)它。在線程內(nèi)部,您可以檢查 X 秒(聽起來像是每 5 秒一次)并逐出條目。地圖需要 <User, long>,其中 long 是驅(qū)逐時(shí)間。您可以創(chuàng)建自己的 put() 和 get() 以及可能的 touch() ,這會(huì)將驅(qū)逐時(shí)間重置為 System.getCurrentMillis();
(我剛剛找到了幾年前使用過的版本。它可以在管理線程的方式上進(jìn)行一些改進(jìn))
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class EvictionList<K>
{
private final ConcurrentHashMap<K, Long> evictionList = new ConcurrentHashMap<K, Long>();
private long evictionTime;
private final EvictionThread t;
public EvictionList(int evictionTimeInSeconds)
{
this.evictionTime = evictionTimeInSeconds * 1000;
t = new EvictionThread(this, evictionTime);
Thread thread = new Thread(t);
thread.start();
}
public void touch(K o)
{
evictionList.put(o, System.currentTimeMillis());
}
public void evict()
{
long current = System.currentTimeMillis();
for (Iterator<K> i=evictionList.keySet().iterator(); i.hasNext();)
{
K k = i.next();
if (current > (evictionList.get(k) + evictionTime) )
{
i.remove();
}
}
}
public void setEvictionTime(int timeInSeconds)
{
evictionTime = timeInSeconds * 1000;
t.setEvictionTime(evictionTime);
}
public Set<K> getKeys()
{
return evictionList.keySet();
}
public void stop()
{
t.shutDown();
}
@Override
protected void finalize()
{
t.shutDown();
}
private class EvictionThread implements Runnable
{
private volatile long evictionTime;
private EvictionList list;
private volatile boolean shouldRun = true;
private EvictionThread(EvictionList list, long evictionTime)
{
this.list = list;
this.evictionTime = evictionTime;
}
public void shutDown()
{
shouldRun = false;
}
public void setEvictionTime(long time)
{
evictionTime = time;
}
public void run()
{
while (shouldRun)
{
try
{
Thread.sleep(evictionTime);
}
catch (Exception ex) {}
list.evict();
}
}
}
}
添加回答
舉報(bào)