我会这样解释:
(...)但不是通过对 Cache.asMap 的集合视图执行的操作
以引用 、 和 。这些是 的三个集合视图。因此,使用它们不应导致访问。entrySet
keySet
values
Map
以下是JUnit(+Mockito)测试,显示了每种情况下的行为。通过 或 不阻止删除条目 (读取或 中的键也不会阻止删除该值)。阅读使用确实算作一种访问权限,正如文档所指定的那样。entrySet
values
entrySet
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());
}