java – Guava CacheBuilder删除监听器
请告诉我我遗失的地方.
我在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秒钟.然后应该调用相应的删除侦听器. 但重要的是,如果我扩展inputDataPool.insertDataIntoPool inputDataPool.insertDataIntoPool(InputDataPacket inputDataPacket){ cache.get(inputDataPacket.getId()); try{ Thread.sleep(2000); }catch(InterruptedException ex){ex.printStackTrace(); } cache.get(inputDataPacket.getId()) } 那么驱逐就像预期的那样发生,并且调用了移除侦听器. 现在我非常无能为力,因为我错过了一些期待这种行为的东西.如果你看到了什么,请帮我看看. 附:请忽略任何拼写错误.也没有进行任何检查,没有使用泛型,因为这只是在测试CacheBuilder功能的阶段. 谢谢 解决方法
正如javadoc和
user guide中所解释的那样,没有任何线程可以确保在延迟过后立即从缓存中删除条目.相反,在写入操作期间删除条目,如果写入很少,则偶尔在读取操作期间删除条目.这是为了实现高吞吐量和低延迟.当然,每次写操作都不会导致清理:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |