javax.cache.Cache.putIfAbsent()方法的使用及代码示例

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

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

Cache.putIfAbsent介绍

[英]Atomically associates the specified key with the given value if it is not already associated with a value.

This is equivalent to:

if (!cache.containsKey(key)) {} 
cache.put(key, value); 
return true; 
} else { 
return false; 
}

except that the action is performed atomically.
[中]如果指定键尚未与某个值关联,则将其与给定值原子关联。
这相当于:

if (!cache.containsKey(key)) {} 
cache.put(key, value); 
return true; 
} else { 
return false; 
}

除了操作是以原子方式执行之外。

代码示例

代码示例来源:origin: killbill/killbill

@Override
public void putIfAbsent(final K key, final V value) {
  cache.putIfAbsent(key, value);
}

代码示例来源:origin: AxonFramework/AxonFramework

@Override
public <K, V> boolean putIfAbsent(K key, V value) {
  return jCache.putIfAbsent(key, value);
}

代码示例来源:origin: spring-projects/spring-framework

@Override
@Nullable
public ValueWrapper putIfAbsent(Object key, @Nullable Object value) {
  boolean set = this.cache.putIfAbsent(key, toStoreValue(value));
  return (set ? null : get(key));
}

代码示例来源:origin: org.springframework/spring-context-support

@Override
@Nullable
public ValueWrapper putIfAbsent(Object key, @Nullable Object value) {
  boolean set = this.cache.putIfAbsent(key, toStoreValue(value));
  return (set ? null : get(key));
}

代码示例来源:origin: killbill/killbill

@Override
public V put(final K key, final V value) throws CacheException {
  V previousValue;
  while (true) {
    previousValue = cache.get(key);
    if (previousValue == null) {
      if (cache.putIfAbsent(key, value)) {
        break;
      }
    } else {
      if (cache.replace(key, value)) {
        break;
      }
    }
  }
  return previousValue;
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void putIfAbsent() {
 expect(cache.putIfAbsent(1, "a")).isTrue();
 changesOf(0, 1, 1, 0);
 expect(cache.putIfAbsent(1, "b")).isFalse();
 changesOf(1, 0, 0, 0);
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testExpiryConfiguration() {
 final AtomicBoolean expiryCreated = new AtomicBoolean(false);
 MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
 configuration.setTypes(String.class, String.class);
 configuration.setExpiryPolicyFactory(() -> {
  expiryCreated.set(true);
  return new CreatedExpiryPolicy(Duration.FIVE_MINUTES);
 });
 Cache<String, String> cache = cacheManager.createCache("cache", configuration);
 cache.putIfAbsent("42", "The Answer");
 cache.putIfAbsent("42", "Or not!?");
 assertThat(expiryCreated.get(), is(true));
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testSimplePutIfAbsentWithLoaderAndWriter_existsInStore() throws Exception {
 testCache.put(1, "un");
 reset(cacheWriter);
 assertThat(testCache.putIfAbsent(1, "one"), is(false));
 assertThat(testCache.get(1), Matchers.<CharSequence>equalTo("un"));
 verifyZeroInteractions(cacheLoader);
 verifyZeroInteractions(cacheWriter);
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testSimplePutIfAbsentWithLoaderAndWriter_existsInSor() throws Exception {
 assertThat(testCache.containsKey(1), is(false));
 assertThat(testCache.putIfAbsent(1, "one"), is(true));
 assertThat(testCache.get(1), Matchers.<CharSequence>equalTo("one"));
 verifyZeroInteractions(cacheLoader);
 verify(cacheWriter, times(1)).write(eq(new Eh107CacheLoaderWriter.Entry<Number, CharSequence>(1, "one")));
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testSimplePutIfAbsentWithLoaderAndWriter_absent() throws Exception {
 assertThat(testCache.containsKey(1), is(false));
 assertThat(testCache.putIfAbsent(1, "one"), is(true));
 assertThat(testCache.get(1), Matchers.<CharSequence>equalTo("one"));
 verifyZeroInteractions(cacheLoader);
 verify(cacheWriter, times(1)).write(eq(new Eh107CacheLoaderWriter.Entry<Number, CharSequence>(1, "one")));
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testSimplePutIfAbsentWithLoaderAndWriter_absent() throws Exception {
 assertThat(testCache.containsKey(1), is(false));
 assertThat(testCache.putIfAbsent(1, "one"), is(true));
 assertThat(testCache.get(1), Matchers.<CharSequence>equalTo("one"));
 verify(cacheLoader).load(1);
 verify(cacheWriter, times(1)).write(eq(new Eh107CacheLoaderWriter.Entry<Number, CharSequence>(1, "one")));
}

代码示例来源:origin: apache/ignite

/**
 * Tries to set the global cleanup node id to current node.
 *
 * @param grid Grid.
 * @param metaCache Meta cache.
 *
 * @return True if successfully set the flag indicating that current node performs the cleanup; otherwise false.
 */
private boolean trySetGlobalCleanupFlag(Ignite grid, final Cache<CleanupNodeId, UUID> metaCache) {
  final UUID localNodeId = grid.cluster().localNode().id();
  while (true) {
    // Get the node performing cleanup.
    UUID nodeId = metaCache.get(CLEANUP_NODE_ID);
    if (nodeId == null) {
      if (metaCache.putIfAbsent(CLEANUP_NODE_ID, localNodeId))
        return true;  // Successfully reserved cleanup to local node.
      // Failed putIfAbsent: someone else may have started cleanup. Retry the check.
      continue;
    }
    if (nodeId.equals(localNodeId))
      return false;  // Current node already performs cleanup.
    if (grid.cluster().node(nodeId) != null)
      return false;  // Another node already performs cleanup and is alive.
    // Node that performs cleanup has disconnected.
    if (metaCache.replace(CLEANUP_NODE_ID, nodeId, localNodeId))
      return true;  // Successfully replaced disconnected node id with our id.
    // Replace failed: someone else started cleanup.
    return false;
  }
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testLoaderConfiguration() throws Exception {
 final AtomicBoolean loaderCreated = new AtomicBoolean(false);
 MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
 configuration.setTypes(String.class, String.class).setReadThrough(true);
 configuration.setCacheLoaderFactory(() -> {
  loaderCreated.set(true);
  return new TestCacheLoader();
 });
 CachingProvider provider = Caching.getCachingProvider();
 CacheManager cacheManager = provider.getCacheManager();
 Cache<String, String> cache = cacheManager.createCache("cache", configuration);
 assertThat(loaderCreated.get(), is(true));
 cache.putIfAbsent("42", "The Answer");
 TestCacheLoader.seen.clear();
 CompletionListenerFuture future = new CompletionListenerFuture();
 cache.loadAll(Collections.singleton("42"), true, future);
 future.get();
 assertThat(TestCacheLoader.seen, contains("42"));
}

代码示例来源:origin: org.axonframework/axon-core

@Override
public <K, V> boolean putIfAbsent(K key, V value) {
  return jCache.putIfAbsent(key, value);
}

代码示例来源:origin: org.apache.camel/camel-jcache

@Override
  void execute(Cache<Object, Object> cache, Exchange exchange) {
    exchange.getIn().setHeader(
      JCacheConstants.RESULT,
      cache.putIfAbsent(
        exchange.getIn().getHeader(JCacheConstants.KEY),
        exchange.getIn().getBody())
    );
  }
},

代码示例来源:origin: org.apache.camel/camel-jcache

@Override
@ManagedOperation(description = "Adds the key to the store")
public boolean add(Object key) {
  return cache.putIfAbsent(key, true);
}

代码示例来源:origin: cache2k/cache2k

@Override
public boolean putIfAbsent(K key, V value) {
 return cache.putIfAbsent(keyTransformer.compact(key), valueTransformer.compact(value));
}

代码示例来源:origin: javax.cache/cache-tests

@Test
public void putIfAbsent_Missing() {
 long now = System.currentTimeMillis();
 Date key = new Date(now);
 Date value = new Date(now);
 assertTrue(cache.putIfAbsent(key, value));
 assertSame(value, cache.get(key));
}

代码示例来源:origin: javax.cache/cache-tests

@Test
public void putIfAbsent_Missing() {
 Long key = System.currentTimeMillis();
 String value = "value" + key;
 assertTrue(cache.putIfAbsent(key, value));
 assertEquals(value, cache.get(key));
}

代码示例来源:origin: org.infinispan/infinispan-core

private <K> void doPutIfAbsent(Supplier<K> keySupplier,
   Cache<K, String> readCache, Cache<K, String> writeCache) {
 K key = keySupplier.get();
 assertEquals(null, readCache.get(key));
 assertTrue(writeCache.putIfAbsent(key, "one"));
 assertEquals("one", readCache.get(key));
 assertFalse(writeCache.putIfAbsent(key, "uno"));
 assertEquals("one", readCache.get(key));
 assertTrue(writeCache.remove(key));
 assertEquals(null, readCache.get(key));
}

相关文章