Java Code Examples for org.ehcache.Cache#putIfAbsent()

The following examples show how to use org.ehcache.Cache#putIfAbsent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestEhcache.java    From elastic-rabbitmq with MIT License 6 votes vote down vote up
@Test
public void testTem() {
    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("preConfigured",
       CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
    .build();

    cacheManager.init();

    Cache<Long, String> preConfigured =
            cacheManager.getCache("preConfigured", Long.class, String.class);

    Cache<Long, String> myCache = cacheManager.createCache("myCache",
            CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)));

    myCache.put(1L, "da one!");
    myCache.putIfAbsent(0L, "ee");
    String value = myCache.get(1L);

    System.out.println("Value is " + value);
    cacheManager.removeCache("preConfigured");
    cacheManager.close();
}
 
Example 2
Source File: EvictionEhcacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimplePutIfAbsentWithEviction() throws Exception {
  Cache<Number, CharSequence> testCache = cacheManager.createCache("testCache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Number.class, CharSequence.class, heap(2))
          .build());

  testCache.putIfAbsent(1, "one");
  testCache.putIfAbsent(2, "two");
  assertThat(testCache.get(1), Matchers.<CharSequence>equalTo("one"));
  assertThat(testCache.get(2), Matchers.<CharSequence>equalTo("two"));

  testCache.putIfAbsent(3, "three");
  testCache.putIfAbsent(4, "four");

  int count = 0;
  for (@SuppressWarnings("unused") Cache.Entry<Number, CharSequence> entry : testCache) {
    count++;
  }
  assertThat(count, is(2));
}
 
Example 3
Source File: BasicCacheOpsMultiThreadedTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
private Callable<?> content() {
  return () -> {
    try (PersistentCacheManager cacheManager = createCacheManager(CLUSTER.getConnectionURI())) {
      Cache<String, Boolean> synCache = cacheManager.getCache(SYN_CACHE_NAME, String.class, Boolean.class);
      Cache<Long, String> customValueCache = cacheManager.getCache(CLUSTERED_CACHE_NAME, Long.class, String.class);
      parallelPuts(customValueCache);
      String firstClientStartKey = "first_client_start", firstClientEndKey = "first_client_end";
      if (synCache.putIfAbsent(firstClientStartKey, true) == null) {
        customValueCache.put(1L, "value");
        assertThat(customValueCache.get(1L), is("value"));
        synCache.put(firstClientEndKey, true);
      } else {
        assertThat(() -> synCache.get(firstClientEndKey), within(Duration.ofSeconds(30)).matches(notNullValue()));
        assertThat(customValueCache.get(1L), is("value"));
      }
      return null;
    }
  };
}
 
Example 4
Source File: SyncService.java    From moon-api-gateway with MIT License 5 votes vote down vote up
/**
 * Create a new app and load it into the cache.
 *
 * @param appInfo This is application information to be newly registered.
 * @return Whether the operation was successful. Not yet applied.
 */
private boolean createApp(AppInfo appInfo) {
    Cache<String, Integer> appDistinction = apiExposeSpec.getAppDistinctionCache();
    appDistinction.putIfAbsent(appInfo.getApiKey(), appInfo.getAppId());

    Cache<Integer, AppInfo> appInfoCaches = apiExposeSpec.getAppInfoCache();
    appInfoCaches.putIfAbsent(appInfo.getAppId(), appInfo);

    return true;
}
 
Example 5
Source File: SimpleEhcacheTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimplePutIfAbsent() throws Exception {
  Cache<Number, CharSequence> testCache = cacheManager.createCache("testCache", newCacheConfigurationBuilder(Number.class, CharSequence.class, heap(10)));

  CharSequence one = testCache.putIfAbsent(1, "one");
  assertThat(one, is(nullValue()));
  CharSequence one_2 = testCache.putIfAbsent(1, "one#2");
  assertThat(one_2, Matchers.<CharSequence>equalTo("one"));
  assertThat(testCache.get(1), Matchers.<CharSequence>equalTo("one"));
}
 
Example 6
Source File: ClusteredCacheExpirationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutIfAbsentExpirationPropagatedToHigherTiers() throws CachePersistenceException {
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = cacheManagerBuilder(oneSecondExpiration());

  try(PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) {
    Cache<Long, String> cache = cacheManager.getCache(CLUSTERED_CACHE, Long.class, String.class);
    cache.put(1L, "value"); // store on the cluster
    cache.putIfAbsent(1L, "newvalue"); // push it up on heap tier
    timeSource.advanceTime(1500); // go after expiration
    assertThat(cache.get(1L)).isEqualTo(null); // the value should have expired
  }
}
 
Example 7
Source File: PutIfAbsentExpiryEhcacheTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Override
protected void insert(Cache<Number, CharSequence> testCache, Map<Number, CharSequence> entries) {
  for (Map.Entry<Number, CharSequence> entry : entries.entrySet()) {
    testCache.putIfAbsent(entry.getKey(), entry.getValue());
  }
}
 
Example 8
Source File: BasicClusteredWriteBehindPassthroughTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
private void putIfAbsent(Cache<Long, String> cache, String value, boolean addToCacheRecords) {
  cache.putIfAbsent(KEY, value);
  if (addToCacheRecords) {
    cacheRecords.add(new Record(KEY, cache.get(KEY)));
  }
}
 
Example 9
Source File: ClusteredEventsTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void testNonExpiringEventSequence() throws TimeoutException {
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
    newCacheManagerBuilder()
      .with(cluster(CLUSTER_URI).autoCreate(s -> s.defaultServerResource("primary-server-resource")))
      .withCache(runningTest.getMethodName(), newCacheConfigurationBuilder(Long.class, String.class,
        newResourcePoolsBuilder().with(clusteredDedicated(16, MemoryUnit.MB))));

  try (PersistentCacheManager driver = clusteredCacheManagerBuilder.build(true)) {
    Cache<Long, String> driverCache = driver.getCache(runningTest.getMethodName(), Long.class, String.class);
    try (PersistentCacheManager observer = clusteredCacheManagerBuilder.build(true)) {
      Cache<Long, String> observerCache = observer.getCache(runningTest.getMethodName(), Long.class, String.class);

      List<CacheEvent<? extends Long, ? extends String>> driverEvents = new ArrayList<>();
      driverCache.getRuntimeConfiguration().registerCacheEventListener(driverEvents::add, EventOrdering.ORDERED, EventFiring.ASYNCHRONOUS, allOf(EventType.class));

      List<CacheEvent<? extends Long, ? extends String>> observerEvents = new ArrayList<>();
      observerCache.getRuntimeConfiguration().registerCacheEventListener(observerEvents::add, EventOrdering.ORDERED, EventFiring.ASYNCHRONOUS, allOf(EventType.class));


      driverCache.put(1L, "foo");
      driverCache.put(1L, "bar");
      driverCache.remove(1L);
      driverCache.putIfAbsent(1L, "baz");
      driverCache.replace(1L, "bat");
      driverCache.replace(1L, "bat", "bag");
      driverCache.remove(1L, "bag");

      @SuppressWarnings("unchecked")
      Matcher<Iterable<? extends CacheEvent<? extends Long, ? extends String>>> expectedSequence = contains(
        created(1L, "foo"),
        updated(1L, "foo", "bar"),
        removed(1L, "bar"),
        created(1L, "baz"),
        updated(1L, "baz", "bat"),
        updated(1L, "bat", "bag"),
        removed(1L, "bag"));

      within(Duration.ofSeconds(10)).runsCleanly(() -> {
        assertThat(driverEvents, expectedSequence);
        assertThat(observerEvents, expectedSequence);
      });
    }
  }
}
 
Example 10
Source File: ClusteredEventsTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void testExpiringEventSequence() throws TimeoutException {
  TestTimeSource timeSource = new TestTimeSource();

  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
    newCacheManagerBuilder()
      .using(new TimeSourceConfiguration(timeSource))
      .with(cluster(CLUSTER_URI).autoCreate(s -> s.defaultServerResource("primary-server-resource")))
      .withCache(runningTest.getMethodName(), newCacheConfigurationBuilder(Long.class, String.class,
        newResourcePoolsBuilder().with(clusteredDedicated(16, MemoryUnit.MB)))
        .withExpiry(timeToLiveExpiration(Duration.ofMillis(1000))));

  try (PersistentCacheManager driver = clusteredCacheManagerBuilder.build(true)) {
    Cache<Long, String> driverCache = driver.getCache(runningTest.getMethodName(), Long.class, String.class);
    try (PersistentCacheManager observer = clusteredCacheManagerBuilder.build(true)) {
      Cache<Long, String> observerCache = observer.getCache(runningTest.getMethodName(), Long.class, String.class);

      List<CacheEvent<? extends Long, ? extends String>> driverEvents = new ArrayList<>();
      driverCache.getRuntimeConfiguration().registerCacheEventListener(driverEvents::add, EventOrdering.ORDERED, EventFiring.ASYNCHRONOUS, allOf(EventType.class));

      List<CacheEvent<? extends Long, ? extends String>> observerEvents = new ArrayList<>();
      observerCache.getRuntimeConfiguration().registerCacheEventListener(observerEvents::add, EventOrdering.ORDERED, EventFiring.ASYNCHRONOUS, allOf(EventType.class));


      driverCache.put(1L, "foo");
      timeSource.advanceTime(1100);
      driverCache.putIfAbsent(1L, "bar");
      timeSource.advanceTime(1100);
      driverCache.remove(1L);
      driverCache.put(1L, "baz");
      timeSource.advanceTime(1100);
      assertThat(driverCache.get(1L), nullValue());

      @SuppressWarnings("unchecked")
      Matcher<Iterable<? extends CacheEvent<? extends Long, ? extends String>>> expectedSequence = contains(
        created(1L, "foo"),
        expired(1L, "foo"),
        created(1L, "bar"),
        expired(1L, "bar"),
        created(1L, "baz"),
        expired(1L, "baz"));

      within(Duration.ofSeconds(10)).runsCleanly(() -> {
        assertThat(driverEvents, expectedSequence);
        assertThat(observerEvents, expectedSequence);
      });
    }
  }
}