PassiveExpiringMap没有使对象过期

问题描述

我期望org.apache.commons.collections4.map.PassiveExpiringMap开箱即用。不幸的是,在按时过期对象的最明显用例中,它对我不起作用。下面的代码创建5秒的过期策略。测试等待10秒钟,这是所有地图对象应过期并删除的时间。但是他们不是。

import org.apache.commons.collections4.map.PassiveExpiringMap;
import org.junit.Assert;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
    
public class PassiveExpiringMapTest {
    @Test
    public void givenDataMap_whenWrappingMapWithPassiveExpiringMap_thenObjectsAreRemovedWhenExpired() {
        
        final Map<String,Integer> m = new HashMap<>();
        m.put("one",Integer.valueOf(1));
        m.put("two",Integer.valueOf(2));
        m.put("three",Integer.valueOf(3));

        PassiveExpiringMap.ConstantTimeToLiveExpirationPolicy<String,Integer>
            expirationPolicy = new PassiveExpiringMap.ConstantTimeToLiveExpirationPolicy<>(
            5,TimeUnit.SECONDS);

        PassiveExpiringMap<String,Integer> expiringMap = new PassiveExpiringMap<>(expirationPolicy,m);

        int initialCapacity = expiringMap.size();
        System.out.println("initialCapacity = " + initialCapacity);
        Assert.assertEquals(3,initialCapacity);

        System.out.println("Sleeping...");
        try { Thread.sleep(10000L); } catch (InterruptedException e) { }

        int updatedCapacity = expiringMap.size();
        System.out.println("updatedCapacity = " + updatedCapacity);
        Integer one = expiringMap.get("one");
        Assert.assertNull(one);
        Assert.assertEquals(0,updatedCapacity);
    }
}

测试失败,并显示以下输出:

initialCapacity = 3
Sleeping...
updatedCapacity = 3

java.lang.AssertionError: expected null,but was:<1>

    at org.junit.Assert.fail(Assert.java:88)
    at org.junit.Assert.failNotNull(Assert.java:755)
    at org.junit.Assert.assertNull(Assert.java:737)
    at org.junit.Assert.assertNull(Assert.java:747)

知道我缺少什么吗?

解决方法

在您的代码中将地图“ m”添加到“ expiringMap”

    PassiveExpiringMap<String,Integer> expiringMap = new PassiveExpiringMap<>(expirationPolicy,m);
    expiringMap.putAll(m);
,

查看PassiveExpiringMap的源代码有助于我弄清楚为什么我的原始版本不起作用。使用地图进行初始化会使内部expirationMap字段为空。 expirationMap必须包含每个对象的条目,以便将过期的对象逐出。为了做到这一点,需要使用 put 方法。下面的修改后的代码有效。请注意,对象是直接添加到expiringMap的,而不是像以前那样添加到HashMap的:

NULL

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...