2

为什么timedCachetest最后一行失败?为什么缓存在 60 秒后不为空?

package com.test.cache;

import java.util.concurrent.TimeUnit;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

public class CacheTest {
    private static final int MAXIMUM_SIZE = 10;
    private static final int CONCURRENCY_LEVEL = 1;
    private static final long EXPIRE_AFTER_ACCESS = 60;
    Cache<String, Thing> cache;
    private static TimeUnit unit = TimeUnit.SECONDS;
    private static long sec = 1000;

    @Before
    public void setUp() throws Exception {
        cache = CacheBuilder.newBuilder().maximumSize(MAXIMUM_SIZE).concurrencyLevel(CONCURRENCY_LEVEL).expireAfterAccess(EXPIRE_AFTER_ACCESS, unit).build();
    }

    @After
    public void tearDown() {
        cache = null;
    }

    @Test
    public void simpleCachetest() {
        String key = "key";
        Integer hc = key.hashCode();
        Thing thing = new Thing(key);
        cache.put(key, thing);
        thing = cache.getIfPresent(key);
        Assert.assertNotNull(thing);
        Assert.assertEquals(hc, thing.getValue());
        Assert.assertEquals(key, thing.getName());
        Assert.assertEquals(1, cache.size());
    }

    @Test
    public void timedCachetest() {
        String key = "key";
        Thing thing = new Thing(key);
        Assert.assertEquals(0, cache.size());
        cache.put(key, thing);
        Assert.assertEquals(1, cache.size());
        try {
            thing = cache.getIfPresent(key);
            long millis = 100 * sec;
            Thread.sleep(millis);
            // cache.invalidateAll();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Assert.assertNotNull(thing);
        Assert.assertEquals(key, thing.getName());
        Assert.assertEquals(0, cache.size());
    }

    class Thing {
        public Thing(String key) {
            this.name = key;
            this.value = key.hashCode();
        }

        public String getName() {
            return name;
        }

        public Integer getValue() {
            return value;
        }

        private String name;
        private Integer value;
    }
}
4

1 回答 1

11

它在CacheBuilderJavadoc 中有说明:

如果 expireAfterWrite 或 expireAfterAccess 被请求,条目可能会在每次缓存修改、偶尔缓存访问或调用 Cache.cleanUp() 时被驱逐。过期的条目可能会被计入 Cache.size(),但永远不会对读取或写入操作可见。

CacheBuilder缓存在被特别请求时进行维护,或者当它可以作为缓存突变的一部分进行维护时,或者偶尔在读取时进行维护。例如,它不会启动一个线程来进行缓存维护,因为 a) 线程相对重量级,并且 b) 某些环境限制了线程的创建。

于 2013-03-07T20:54:55.207 回答