请告诉我我遗失的地方.
我在DataPool中有一个CacheBuilder构建的缓存. 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 nanosec之后到期.所以当第二次调用inputDataPool.insertDataIntoPool时,第一次插入的数据将被撤离,因为它必须已经过期,因为调用是在插入2秒钟.然后应该调用相应的删除侦听器.
但这不会发生.我查看了缓存统计信息,并且evictionCount始终为零,无论调用cache.get(id)多少时间.
但重要的是,如果我扩展inputDataPool.insertDataIntoPool
inputDataPool.insertDataIntoPool(InputDataPacket inputDataPacket){
cache.get(inputDataPacket.getId());
try{
Thread.sleep(2000);
}catch(InterruptedException ex){ex.printStackTrace();
}
cache.get(inputDataPacket.getId())
}
那么驱逐就像预期的那样发生,并且调用了移除侦听器.
现在我非常无能为力,因为我错过了一些期待这种行为的东西.如果你看到了什么,请帮我看看.
附:请忽略任何拼写错误.也没有进行任何检查,没有使用泛型,因为这只是在测试CacheBuilder功能的阶段.
谢谢