未调用番石榴缓存RemovalListener

问题描述 投票:0回答:1

我创建了一个具有以下参数的缓存:

cacheTempFiles = CacheBuilder.newBuilder().maximumSize(250).expireAfterWrite(15, TimeUnit.SECONDS).removalListener(new RemovalListener<String, Path>()
        {

            @Override
            public void onRemoval(RemovalNotification<String, Path> notification)
            {
                deleteTemporaryFile(notification.getValue());

            }
        }).build();

而且,我每2分钟打一次电话cacheTempFiles.cleanUp();。但是,似乎从未调用过onRemoval

我的实现中缺少什么?

java caching guava
1个回答
0
投票
它肯定可以工作,请参见下面的示例:

@Test public void shouldCallRemovalListener() { AtomicInteger counter = new AtomicInteger(); MutableClock clock = MutableClock.epochUTC(); Ticker ticker = new Ticker() { @Override public long read() { return TimeUnit.MILLISECONDS.toNanos(clock.millis()); } }; Path tmpPath = Path.of("/tmp"); Cache<String, Path> cacheTempFiles = CacheBuilder.newBuilder() .ticker(ticker) .maximumSize(250) .expireAfterWrite(15, TimeUnit.SECONDS) .removalListener( (RemovalNotification<String, Path> notification) -> System.out.println(String.format( "Delete '%s -> %s' (%d times)", notification.getKey(), notification.getValue(), counter.incrementAndGet()))) .build(); cacheTempFiles.put("tmp", tmpPath); assertThat(cacheTempFiles.asMap()).containsOnly(Assertions.entry("tmp", tmpPath)); assertThat(counter).hasValue(0); clock.add(Duration.ofSeconds(20)); cacheTempFiles.cleanUp(); assertThat(cacheTempFiles.asMap()).isEmpty(); assertThat(counter).hasValue(1); }

通过并输出Delete 'tmp -> /tmp' (1 times)
© www.soinside.com 2019 - 2024. All rights reserved.