com.github.benmanes.caffeine.cache.Cache.asMap()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(11.2k)|赞(0)|评价(0)|浏览(312)

本文整理了Java中com.github.benmanes.caffeine.cache.Cache.asMap()方法的一些代码示例,展示了Cache.asMap()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Cache.asMap()方法的具体详情如下:
包路径:com.github.benmanes.caffeine.cache.Cache
类名称:Cache
方法名:asMap

Cache.asMap介绍

[英]Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to the map directly affect the cache.

Iterators from the returned map are at least weakly consistent: they are safe for concurrent use, but if the cache is modified (including by eviction) after the iterator is created, it is undefined which of the changes (if any) will be reflected in that iterator.
[中]作为线程安全映射返回存储在此缓存中的项的视图。对映射所做的修改直接影响缓存。
返回映射中的迭代器至少是弱一致的:它们对于并发使用是安全的,但是如果在创建迭代器之后修改了缓存(包括通过逐出),则未定义哪些更改(如果有的话)将反映在该迭代器中。

代码示例

代码示例来源:origin: apache/incubator-druid

@Override
public void close(String namespace)
{
 if (config.isEvictOnClose()) {
  cache.asMap().keySet().removeIf(key -> key.namespace.equals(namespace));
 }
}

代码示例来源:origin: ben-manes/caffeine

/** Returns the underlying bounded cache, or null if not applicable. */
private static @Nullable BoundedLocalCache<?, ?> unwrap(Cache<?, ?> cache) {
 ConcurrentMap<?, ?> map = cache.asMap();
 if (map instanceof LocalAsyncLoadingCache.AsMapView<?, ?>) {
  map = ((LocalAsyncLoadingCache.AsMapView<?, ?>) cache.asMap()).delegate;
 }
 return (map instanceof BoundedLocalCache<?, ?>)
   ? (BoundedLocalCache<?, ?>) map
   : null;
}

代码示例来源:origin: apache/incubator-druid

public static void forceRandomSeed(CaffeineCache cache) throws Exception
 {
  final Map map = cache.getCache().asMap();
  final Method getFrequencySketch = map.getClass().getDeclaredMethod("frequencySketch");
  getFrequencySketch.setAccessible(true);
  final Object frequencySketch = getFrequencySketch.invoke(map);
  final Field seedField = frequencySketch.getClass().getDeclaredField("randomSeed");
  seedField.setAccessible(true);
  seedField.setInt(frequencySketch, RANDOM_SEED);
 }
}

代码示例来源:origin: ben-manes/caffeine

private void checkContainsInOrder(Cache<Integer, Integer> cache, Integer... expect) {
 cache.cleanUp();
 List<Integer> evictionList = ImmutableList.copyOf(
   cache.policy().eviction().get().coldest(Integer.MAX_VALUE).keySet());
 assertThat(cache.asMap().size(), is(equalTo(expect.length)));
 assertThat(cache.asMap().keySet(), containsInAnyOrder(expect));
 assertThat(evictionList, is(equalTo(asList(expect))));
}

代码示例来源:origin: ben-manes/caffeine

@Test(dataProvider = "caches")
@CacheSpec(implementation = Implementation.Caffeine, maximumSize = Maximum.FULL,
  weigher = CacheWeigher.COLLECTION, population = Population.EMPTY,
  keys = ReferenceType.STRONG, values = ReferenceType.STRONG)
public void replaceConditionally_sameWeight(
  Cache<String, List<Integer>> cache, CacheContext context, Eviction<?, ?> eviction) {
 cache.putAll(ImmutableMap.of("a", asList(1, 2, 3), "b", asList(1)));
 assertThat(cache.asMap().replace("a", asList(1, 2, 3), asList(4, 5, 6)), is(true));
 assertThat(cache.estimatedSize(), is(2L));
 assertThat(eviction.weightedSize().getAsLong(), is(4L));
}

代码示例来源:origin: ben-manes/caffeine

@Test(dataProvider = "caches")
@CacheSpec(implementation = Implementation.Caffeine, maximumSize = Maximum.FULL,
  weigher = CacheWeigher.COLLECTION, population = Population.EMPTY,
  keys = ReferenceType.STRONG, values = ReferenceType.STRONG)
public void remove(Cache<String, List<Integer>> cache,
  CacheContext context, Eviction<?, ?> eviction) {
 cache.putAll(ImmutableMap.of("a", asList(1, 2, 3), "b", asList(1)));
 assertThat(cache.asMap().remove("a"), is(asList(1, 2, 3)));
 assertThat(cache.estimatedSize(), is(1L));
 assertThat(eviction.weightedSize().getAsLong(), is(1L));
}

代码示例来源:origin: ben-manes/caffeine

@Test(dataProvider = "caches")
@CacheSpec(implementation = Implementation.Caffeine, maximumSize = Maximum.FULL,
  weigher = CacheWeigher.COLLECTION, population = Population.EMPTY,
  keys = ReferenceType.STRONG, values = ReferenceType.STRONG)
public void removeConditionally_fails(
  Cache<String, List<Integer>> cache, CacheContext context, Eviction<?, ?> eviction) {
 cache.putAll(ImmutableMap.of("a", asList(1, 2, 3), "b", asList(1)));
 assertThat(cache.asMap().remove("a", asList(-1, -2, -3)), is(false));
 assertThat(cache.estimatedSize(), is(2L));
 assertThat(eviction.weightedSize().getAsLong(), is(4L));
}

代码示例来源:origin: ben-manes/caffeine

@Test(dataProvider = "caches")
@CacheSpec(implementation = Implementation.Caffeine, maximumSize = Maximum.FULL,
  weigher = CacheWeigher.COLLECTION, population = Population.EMPTY,
  keys = ReferenceType.STRONG, values = ReferenceType.STRONG)
public void replace_sameWeight(Cache<String, List<Integer>> cache,
  CacheContext context, Eviction<?, ?> eviction) {
 cache.putAll(ImmutableMap.of("a", asList(1, 2, 3), "b", asList(1)));
 cache.asMap().replace("a", asList(-1, -2, -3));
 assertThat(cache.estimatedSize(), is(2L));
 assertThat(eviction.weightedSize().getAsLong(), is(4L));
}

代码示例来源:origin: ben-manes/caffeine

@Test(dataProvider = "caches")
@CacheSpec(implementation = Implementation.Caffeine, maximumSize = Maximum.FULL,
  weigher = CacheWeigher.COLLECTION, population = Population.EMPTY,
  keys = ReferenceType.STRONG, values = ReferenceType.STRONG)
public void replace_changeWeight(Cache<String, List<Integer>> cache,
  CacheContext context, Eviction<?, ?> eviction) {
 cache.putAll(ImmutableMap.of("a", asList(1, 2, 3), "b", asList(1)));
 cache.asMap().replace("a", asList(-1, -2, -3, -4));
 assertThat(cache.estimatedSize(), is(2L));
 assertThat(eviction.weightedSize().getAsLong(), is(5L));
}

代码示例来源:origin: ben-manes/caffeine

@Test(dataProvider = "caches")
@CacheSpec(implementation = Implementation.Caffeine,
  maximumSize = Maximum.FULL, weigher = CacheWeigher.TEN)
public void weightedSize(Cache<Integer, Integer> cache, CacheContext context,
  Eviction<Integer, Integer> eviction) {
 long weightedSize = 0;
 for (Integer key : cache.asMap().keySet()) {
  weightedSize += eviction.weightOf(key).getAsInt();
 }
 assertThat(weightedSize, is(eviction.weightedSize().getAsLong()));
 assertThat(eviction.weightedSize().getAsLong(), is(10 * cache.estimatedSize()));
}

代码示例来源:origin: ben-manes/caffeine

@Test(dataProvider = "caches")
@CacheSpec(values = {ReferenceType.WEAK, ReferenceType.SOFT}, population = Population.FULL)
public void identity_values(Cache<Integer, Integer> cache, CacheContext context) {
 @SuppressWarnings("deprecation")
 Integer value = new Integer(context.original().get(context.firstKey()));
 assertThat(cache.asMap().containsValue(value), is(false));
}

代码示例来源:origin: ben-manes/caffeine

@Test(dataProvider = "caches")
@CacheSpec(population = { Population.PARTIAL, Population.FULL })
public void invalidateAll_partial(Cache<Integer, Integer> cache, CacheContext context) {
 List<Integer> keys = cache.asMap().keySet().stream()
   .filter(i -> ((i % 2) == 0))
   .collect(Collectors.toList());
 cache.invalidateAll(keys);
 assertThat(cache.estimatedSize(), is(context.initialSize() - keys.size()));
 assertThat(cache, hasRemovalNotifications(context, keys.size(), RemovalCause.EXPLICIT));
 verifyWriter(context, (verifier, writer) -> {
  verifier.deletedAll(Maps.filterKeys(context.original(), Predicates.in(keys)), RemovalCause.EXPLICIT);
 });
}

代码示例来源:origin: ben-manes/caffeine

@CheckNoStats
@Test(dataProvider = "caches", expectedExceptions = DeleteException.class)
@CacheSpec(implementation = Implementation.Caffeine, keys = ReferenceType.STRONG,
  population = { Population.SINGLETON, Population.PARTIAL, Population.FULL },
  compute = Compute.SYNC, writer = Writer.EXCEPTIONAL, removalListener = Listener.REJECTING)
public void invalidateAll_full_writerFails(Cache<Integer, Integer> cache, CacheContext context) {
 try {
  cache.invalidateAll();
 } finally {
  assertThat(cache.asMap(), equalTo(context.original()));
 }
}

代码示例来源:origin: ben-manes/caffeine

@Test(dataProvider = "caches")
@CacheSpec(keys = ReferenceType.STRONG, values = {ReferenceType.WEAK, ReferenceType.SOFT},
  implementation = Implementation.Caffeine, expireAfterAccess = Expire.DISABLED,
  expireAfterWrite = Expire.DISABLED, maximumSize = Maximum.DISABLED,
  weigher = CacheWeigher.DEFAULT, population = Population.FULL, stats = Stats.ENABLED,
  compute = Compute.SYNC, removalListener = Listener.CONSUMING, writer = Writer.EXCEPTIONAL)
public void cleanUp_writerFails(Cache<Integer, Integer> cache, CacheContext context) {
 context.clear();
 GcFinalization.awaitFullGc();
 cache.cleanUp();
 context.disableRejectingCacheWriter();
 assertThat(cache.asMap().isEmpty(), is(false));
}

代码示例来源:origin: ben-manes/caffeine

@CheckNoStats
@Test(dataProvider = "caches", expectedExceptions = WriteException.class)
@CacheSpec(implementation = Implementation.Caffeine, keys = ReferenceType.STRONG,
  compute = Compute.SYNC, writer = Writer.EXCEPTIONAL, removalListener = Listener.REJECTING)
public void putAll_insert_writerFails(Cache<Integer, Integer> cache, CacheContext context) {
 try {
  cache.putAll(context.absent());
 } finally {
  assertThat(cache.asMap(), equalTo(context.original()));
 }
}

代码示例来源:origin: ben-manes/caffeine

@CheckNoStats
@Test(dataProvider = "caches", expectedExceptions = DeleteException.class)
@CacheSpec(implementation = Implementation.Caffeine, keys = ReferenceType.STRONG,
  population = { Population.SINGLETON, Population.PARTIAL, Population.FULL },
  compute = Compute.SYNC, writer = Writer.EXCEPTIONAL, removalListener = Listener.REJECTING)
public void invalidate_writerFails(Cache<Integer, Integer> cache, CacheContext context) {
 try {
  cache.invalidate(context.middleKey());
 } finally {
  assertThat(cache.asMap(), equalTo(context.original()));
 }
}

代码示例来源:origin: ben-manes/caffeine

@CheckNoStats
@Test(dataProvider = "caches", expectedExceptions = DeleteException.class)
@CacheSpec(implementation = Implementation.Caffeine, keys = ReferenceType.STRONG,
  population = { Population.SINGLETON, Population.PARTIAL, Population.FULL },
  compute = Compute.SYNC, writer = Writer.EXCEPTIONAL, removalListener = Listener.REJECTING)
public void invalidateAll_partial_writerFails(Cache<Integer, Integer> cache, CacheContext context) {
 try {
  cache.invalidateAll(context.firstMiddleLastKeys());
 } finally {
  assertThat(cache.asMap(), equalTo(context.original()));
 }
}

代码示例来源:origin: ben-manes/caffeine

@Test(dataProvider = "caches")
@CacheSpec(implementation = Implementation.Caffeine, requiresWeakOrSoft = true,
  expireAfterAccess = Expire.DISABLED, expireAfterWrite = Expire.DISABLED,
  maximumSize = Maximum.UNREACHABLE, weigher = CacheWeigher.COLLECTION,
  population = Population.EMPTY, stats = Stats.ENABLED, removalListener = Listener.DEFAULT,
  writer = Writer.DISABLED)
public void compute_weighted(Cache<Integer, List<Integer>> cache, CacheContext context) {
 Integer key = context.absentKey();
 cache.put(key, ImmutableList.of(1));
 GcFinalization.awaitFullGc();
 cache.asMap().compute(key, (k, v) -> ImmutableList.of(1, 2, 3));
 assertThat(cache.policy().eviction().get().weightedSize().getAsLong(), is(3L));
}

代码示例来源:origin: ben-manes/caffeine

private static <K, V> ConcurrentMap<K, V> map() {
 return Caffeine.newBuilder()
   .maximumSize(Integer.MAX_VALUE)
   .<K, V>build().asMap();
}

代码示例来源:origin: ben-manes/caffeine

private static void addBoundedTests(TestSuite suite) throws Exception {
 suite.addTest(MapTestFactory.suite("BoundedCache", () -> {
  Cache<String, String> cache = Caffeine.newBuilder().maximumSize(Long.MAX_VALUE).build();
  return cache.asMap();
 }));
 suite.addTest(MapTestFactory.suite("BoundedAsyncCache", () -> {
  AsyncLoadingCache<String, String> cache = Caffeine.newBuilder()
    .maximumSize(Long.MAX_VALUE)
    .buildAsync(key -> null);
  return cache.synchronous().asMap();
 }));
}

相关文章