我会这样解释:
(...) 但不是通过对 Cache.asMap 的集合视图的操作
指entrySet
, keySet
, 和values
. 这些是 a 的三个集合视图Map
。因此,使用它们不应导致访问。
以下是 JUnit (+Mockito) 测试,它们显示了每种情况下的行为。通过entrySet
or读取值values
不会阻止条目被删除(也不会从entrySet
or读取键keySet
)。正如文档指定的那样,阅读使用asMap().get()
确实算作访问。
设置
private Ticker ticker = Mockito.mock(Ticker.class);
@SuppressWarnings({"unchecked"})
private RemovalListener<String, String> removalListener = Mockito.mock(RemovalListener.class);
private Cache<String, String> cache = CacheBuilder.newBuilder()
.expireAfterAccess(5, TimeUnit.SECONDS)
.removalListener(removalListener)
.ticker(ticker)
.build();
entrySet
@Test
public void testEntrySetAccessDoesNotCountAsAccess() {
//write
when(ticker.read()).thenReturn(TimeUnit.SECONDS.toNanos(0));
cache.put("foo", "bar");
//read
when(ticker.read()).thenReturn(TimeUnit.SECONDS.toNanos(4));
cache.asMap().entrySet().iterator().next().getValue();
cache.asMap().entrySet().iterator().next().getKey();
//maintenance
when(ticker.read()).thenReturn(TimeUnit.SECONDS.toNanos(6));
cache.cleanUp();
verify(removalListener).onRemoval(Mockito.<RemovalNotification<String,String>>any());
}
keySet
@Test
public void testKeySetAccessDoesNotCountAsAccess() {
//write
when(ticker.read()).thenReturn(TimeUnit.SECONDS.toNanos(0));
cache.put("foo", "bar");
//read
when(ticker.read()).thenReturn(TimeUnit.SECONDS.toNanos(4));
cache.asMap().keySet().iterator().next();
//maintenance
when(ticker.read()).thenReturn(TimeUnit.SECONDS.toNanos(6));
cache.cleanUp();
verify(removalListener).onRemoval(Mockito.<RemovalNotification<String,String>>any());
}
values
@Test
public void testValuesAccessDoesNotCountAsAccess() {
//write
when(ticker.read()).thenReturn(TimeUnit.SECONDS.toNanos(0));
cache.put("foo", "bar");
//read
when(ticker.read()).thenReturn(TimeUnit.SECONDS.toNanos(4));
cache.asMap().values().iterator().next();
//maintenance
when(ticker.read()).thenReturn(TimeUnit.SECONDS.toNanos(6));
cache.cleanUp();
verify(removalListener).onRemoval(Mockito.<RemovalNotification<String,String>>any());
}
asMap().get()
@Test
public void testMapGetAccessCountsAsAccess() {
//write
when(ticker.read()).thenReturn(TimeUnit.SECONDS.toNanos(0));
cache.put("foo", "bar");
//read
when(ticker.read()).thenReturn(TimeUnit.SECONDS.toNanos(4));
cache.asMap().get("foo");
//maintenance
when(ticker.read()).thenReturn(TimeUnit.SECONDS.toNanos(6));
cache.cleanUp();
verify(removalListener, never()).onRemoval(Mockito.<RemovalNotification<String,String>>any());
}