Guava CacheBuilder removal listener

后端 未结 2 1237
情话喂你
情话喂你 2021-01-14 05:18

Please show me where I\'m missing something.

I have a cache build by CacheBuilder inside a DataPool. DataPool is a singleton object whose instance various thread can

2条回答
  •  旧时难觅i
    2021-01-14 06:02

    I had the same issue and I could find this at guava's documentation for CacheBuilder.removalListener

    Warning: after invoking this method, do not continue to use this cache builder reference; instead use the reference this method returns. At runtime, these point to the same instance, but only the returned reference has the correct generic type information so as to ensure type safety. For best results, use the standard method-chaining idiom illustrated in the class documentation above, configuring a builder and building your cache in a single statement. Failure to heed this advice can result in a ClassCastException being thrown by a cache operation at some undefined point in the future.

    So by changing your code to use the builder reference that is called after adding the removalListnener this problem can be resolved

     CacheBuilder builder=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());
                                        }
    
                                    }}
                        );
       cache=builder.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);
    
                            }
    
                        });
    

    This problem will be resolved. It is kind of wired but I guess it is what it is :)

提交回复
热议问题