請告訴我我錯在哪裏。Guava CacheBuilder刪除監聽器
我有一個由CacheBuilder在DataPool內部構建的緩存。 DataPool是一個單例對象,其實例各種線程都可以獲取和操作。現在我有一個線程產生數據並將其添加到上述緩存中。
顯示代碼的相關部分:
private InputDataPool(){
cache=CacheBuilder.newBuilder().expireAfterWrite(1000, TimeUnit.NANOSECONDS).removalListener(
new RemovalListener(){
{
logger.debug("Removal Listener created");
}
public void onRemoval(RemovalNotification notification) {
System.out.println("Going to remove data from InputDataPool");
logger.info("Following data is being removed:"+notification.getKey());
if(notification.getCause()==RemovalCause.EXPIRED)
{
logger.fatal("This data expired:"+notification.getKey());
}else
{
logger.fatal("This data didn't expired but evacuated intentionally"+notification.getKey());
}
}}
).build(new CacheLoader(){
@Override
public Object load(Object key) throws Exception {
logger.info("Following data being loaded"+(Integer)key);
Integer uniqueId=(Integer)key;
return InputDataPool.getInstance().getAndRemoveDataFromPool(uniqueId);
}
});
}
public static InputDataPool getInstance(){
if(clsInputDataPool==null){
synchronized(InputDataPool.class){
if(clsInputDataPool==null)
{
clsInputDataPool=new InputDataPool();
}
}
}
return clsInputDataPool;
}
從說線程正在發出的呼籲很簡單,只要
while(true){
inputDataPool.insertDataIntoPool(inputDataPacket);
//call some logic which comes with inputDataPacket and sleep for 2 seconds.
}
何inputDataPool.insertDataIntoPool就像
inputDataPool.insertDataIntoPool(InputDataPacket inputDataPacket){
cache.get(inputDataPacket.getId());
}
現在的問題是,緩存中的元素應該在1000納秒之後過期。因此,當第二次調用inputDataPool.insertDataIntoPool時,第一次插入的數據將被撤出,因爲它在插入2秒後正在調用,因此它必須已經過期,然後應該調用相應的Removal Listener。 但是這沒有發生。我查看緩存統計信息,並且無論調用cache.get(id)多少時間,evictionCount始終爲零。
但重要的是,如果我延長inputDataPool.insertDataIntoPool
inputDataPool.insertDataIntoPool(InputDataPacket inputDataPacket){
cache.get(inputDataPacket.getId());
try{
Thread.sleep(2000);
}catch(InterruptedException ex){ex.printStackTrace();
}
cache.get(inputDataPacket.getId())
}
然後驅逐發生與去除聽衆被稱爲預期。
現在我非常無能爲力,因爲我錯過了期待這種行爲的東西。如果你看到什麼,請幫我看看。
P.S.請忽略任何輸入錯誤。也沒有進行檢查,沒有使用泛型,因爲這只是測試CacheBuilder功能的階段。
感謝
同意!但是在我的實施中,是不是必須有一個統一的政策。正如我所提到的,當我在某次睡眠後重新觸發cache.get(key)時,它會逐出,但是如果我想出了不同的鍵並在同樣的時間間隔後再次觸發cache.get(key),它不會逐出。儘管代碼可以與我一起使用,但我會經歷它,您是否可以同時澄清這一點,他們是否會使用一些隨意的方法來處理驅逐問題。 – mawia
嘗試使用cleanUp()代替get() –
它不是「隨機」,而是「盡力而爲」。此外,在具有高緩存吞吐量的實際應用程序中,您無需擔心 - 緩存維護將會頻繁發生。 –