【发布时间】:2012-05-16 21:06:25
【问题描述】:
请告诉我我遗漏了什么。
我在 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 纳秒后过期。所以当第二次调用 inputDataPool.insertDataIntoPool 时,第一次插入的数据将被撤出,因为它必须在调用时过期插入后 2 秒后,应调用相应的移除侦听器。 但这并没有发生。我查看了缓存统计信息,无论调用多少时间 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())
}
然后驱逐按预期发生,并调用删除侦听器。
现在我非常无能为力,因为我错过了一些可以期待这种行为的东西。请帮我看看,如果你看到了什么。
附:请忽略任何拼写错误。也没有进行检查,没有使用泛型,因为这只是在测试 CacheBuilder 功能的阶段。
谢谢
【问题讨论】: