org.ehcache.config.builders.ExpiryPolicyBuilder Java Examples

The following examples show how to use org.ehcache.config.builders.ExpiryPolicyBuilder. 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: AbstractOffHeapStoreTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidateKeyPresent() throws Exception {
  offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L)));

  offHeapStore.put("1", "one");

  final AtomicReference<Store.ValueHolder<String>> invalidated = new AtomicReference<>();
  offHeapStore.setInvalidationListener((key, valueHolder) -> {
    valueHolder.get();
    invalidated.set(valueHolder);
  });

  offHeapStore.invalidate("1");
  assertThat(invalidated.get().get(), equalTo("one"));
  validateStats(offHeapStore, EnumSet.of(LowerCachingTierOperationsOutcome.InvalidateOutcome.REMOVED));

  assertThat(offHeapStore.get("1"), is(nullValue()));
}
 
Example #2
Source File: AbstractOffHeapStoreTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testInstallMapping() throws Exception {
  offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L)));

  assertThat(offHeapStore.installMapping("1", key -> new SimpleValueHolder<>("one", timeSource.getTimeMillis(), 15)).get(), equalTo("one"));

  validateStats(offHeapStore, EnumSet.of(LowerCachingTierOperationsOutcome.InstallMappingOutcome.PUT));

  timeSource.advanceTime(20);

  try {
    offHeapStore.installMapping("1", key -> new SimpleValueHolder<>("un", timeSource.getTimeMillis(), 15));
    fail("expected AssertionError");
  } catch (AssertionError ae) {
    // expected
  }
}
 
Example #3
Source File: AbstractChainResolverTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFullResolveForMultipleKeysAndOperations() {
  //create a random mix of operations
  Chain chain = getEntryFromOperations(
    new PutIfAbsentOperation<>(1L, "Albin", 0L),
    new PutOperation<>(1L, "Suresh", 0L),
    new PutOperation<>(1L, "Matthew", 0L),
    new PutOperation<>(2L, "Melvin", 0L),
    new ReplaceOperation<>(1L, "Joseph", 0L),
    new RemoveOperation<>(2L, 0L),
    new ConditionalRemoveOperation<>(1L, "Albin", 0L),
    new PutOperation<>(1L, "Gregory", 0L),
    new ConditionalReplaceOperation<>(1L, "Albin", "Abraham", 0L),
    new RemoveOperation<>(1L, 0L),
    new PutIfAbsentOperation<>(2L, "Albin", 0L));

  ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration());
  Map<Long, Store.ValueHolder<String>> resolved = resolver.resolveAll(chain, 0L);
  assertThat(resolved.get(2L).get(), is("Albin"));
}
 
Example #4
Source File: TokenProviderUtility.java    From Insights with Apache License 2.0 6 votes vote down vote up
/**
 * used to initilize cache
 */
@PostConstruct
public void initilizeTokenCache() {
	log.debug("Inside initilizeTokenCache of tokenProviderUtility ==== ");
	if (TokenProviderUtility.cacheManager == null) {
		TokenProviderUtility.cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
				.withCache("tokenCache",
						CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
								ResourcePoolsBuilder.newResourcePoolsBuilder().heap(30, EntryUnit.ENTRIES)
										.offheap(10, MemoryUnit.MB)))
				.build();

		TokenProviderUtility.cacheManager.init();
		if (TokenProviderUtility.tokenCache == null) {
			TokenProviderUtility.tokenCache = cacheManager.createCache("pipeline",
					CacheConfigurationBuilder
							.newCacheConfigurationBuilder(String.class, String.class,
									ResourcePoolsBuilder.heap(TraceabilityConstants.PIPELINE_CACHE_HEAP_SIZE_BYTES))
							.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(
									Duration.ofSeconds(TraceabilityConstants.PIPELINE_CACHE_EXPIRY_IN_SEC))));
		}
	}
}
 
Example #5
Source File: CacheConfiguration.java    From TeamDojo with Apache License 2.0 6 votes vote down vote up
public CacheConfiguration(JHipsterProperties jHipsterProperties) {
    BeanClassLoaderAwareJCacheRegionFactory.setBeanClassLoader(this.getClass().getClassLoader());
    JHipsterProperties.Cache.Ehcache ehcache =
        jHipsterProperties.getCache().getEhcache();

    jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration(
        CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class,
            ResourcePoolsBuilder.heap(ehcache.getMaxEntries()))
            .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(ehcache.getTimeToLiveSeconds())))
            .build());
}
 
Example #6
Source File: DefaultTierStatisticsTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
  CacheConfiguration<Long, String> cacheConfiguration =
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES))
      .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION)))
      .withService(new StoreStatisticsConfiguration(true)) // explicitly enable statistics
      .build();

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("aCache", cacheConfiguration)
    .using(new TimeSourceConfiguration(timeSource))
    .build(true);

  cache = cacheManager.getCache("aCache", Long.class, String.class);

  onHeap = new DefaultTierStatistics(cache, "OnHeap");
}
 
Example #7
Source File: BaseOnHeapStoreTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testComputeReplaceFalse() throws Exception {
  TestTimeSource timeSource = new TestTimeSource();
  OnHeapStore<String, String> store = newStore(timeSource, ExpiryPolicyBuilder.noExpiration());

  store.put("key", "value");
  ValueHolder<String> installedHolder = store.get("key");
  long createTime = installedHolder.creationTime();
  long accessTime = installedHolder.lastAccessTime();
  timeSource.advanceTime(1);

  ValueHolder<String> newValue = store.computeAndGet("key", (mappedKey, mappedValue) -> mappedValue, () -> false, () -> false);

  assertThat(newValue.get(), equalTo("value"));
  assertThat(createTime, equalTo(newValue.creationTime()));
  assertThat(accessTime + 1, equalTo(newValue.lastAccessTime()));
  StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.ComputeOutcome.HIT));
}
 
Example #8
Source File: DefaultCacheStatisticsTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
  CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
    .newEventListenerConfiguration((CacheEventListener<Long, String>) expirations::add, EventType.EXPIRED)
    .unordered()
    .synchronous();

  CacheConfiguration<Long, String> cacheConfiguration =
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
      .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION)))
      .withService(cacheEventListenerConfiguration)
      .withService(new StoreStatisticsConfiguration(enableStoreStatistics))
      .build();

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("aCache", cacheConfiguration)
    .using(new TimeSourceConfiguration(timeSource))
    .build(true);

  cache = (InternalCache<Long, String>) cacheManager.getCache("aCache", Long.class, String.class);

  cacheStatistics = new DefaultCacheStatistics(cache);
}
 
Example #9
Source File: AbstractChainResolverTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompactForMultipleKeysAndOperations() {
  //create a random mix of operations
  ServerStoreProxy.ChainEntry chain = getEntryFromOperations(
    new PutIfAbsentOperation<>(1L, "Albin", 0L),
    new PutOperation<>(1L, "Suresh", 0L),
    new PutOperation<>(1L, "Matthew", 0L),
    new PutOperation<>(2L, "Melvin", 0L),
    new ReplaceOperation<>(1L, "Joseph", 0L),
    new RemoveOperation<>(2L, 0L),
    new ConditionalRemoveOperation<>(1L, "Albin", 0L),
    new PutOperation<>(1L, "Gregory", 0L),
    new ConditionalReplaceOperation<>(1L, "Albin", "Abraham", 0L),
    new RemoveOperation<>(1L, 0L),
    new PutIfAbsentOperation<>(2L, "Albin", 0L));

  ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration());
  resolver.compact(chain);
  verify(chain).replaceAtHead(argThat(contains(operation(new PutOperation<>(2L, "Albin", 0L)))));
}
 
Example #10
Source File: OnHeapEvictionStrategyTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void customExpiryGet() {
  Cache<Integer, String> cache = createCache(
    ExpiryPolicyBuilder.expiry()
  .create(ExpiryPolicy.INFINITE)
  .update(Duration.ofMillis(100))
  .access((Duration) null)
  .build());

  cache.put(1, "a");

  assertThat(cache.get(1)).isEqualTo("a");

  cache.put(1, "b");

  timeSource.setTimeMillis(100);

  assertThat(cache.get(1)).isNull();
}
 
Example #11
Source File: OnHeapEvictionStrategyTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void customExpiryPut() {
  Cache<Integer, String> cache = createCache(
    ExpiryPolicyBuilder.expiry()
      .create(ExpiryPolicy.INFINITE)
      .update(Duration.ofMillis(100))
      .access((Duration) null)
      .build());

  cache.put(1, "a"); // create
  cache.put(1, "b"); // update that will expire

  timeSource.setTimeMillis(100);

  assertThat(cache.putIfAbsent(1, "d")).isNull(); // expires since update
}
 
Example #12
Source File: ExpiryChainResolverTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test @Override
public void testResolveDecodesOperationValueOnlyOnDemand() {
  ServerStoreProxy.ChainEntry chain = getEntryFromOperations(
    new PutOperation<>(1L, "Albin", 1),
    new PutOperation<>(1L, "Suresh", 2),
    new PutOperation<>(1L, "Matthew", 3));

  CountingLongSerializer keySerializer = new CountingLongSerializer();
  CountingStringSerializer valueSerializer = new CountingStringSerializer();
  OperationsCodec<Long, String> customCodec = new OperationsCodec<>(keySerializer, valueSerializer);
  ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration(), customCodec);
  resolver.resolve(chain, 1L, 0L);

  assertThat(keySerializer.decodeCount, is(3));
  assertThat(valueSerializer.decodeCount, is(3));
  assertThat(valueSerializer.encodeCount, is(0));
  assertThat(keySerializer.encodeCount, is(1)); //One encode from encoding the resolved operation's key
}
 
Example #13
Source File: AbstractOffHeapStoreTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testExpiryEventFiredOnExpiredCachedEntry() throws StoreAccessException {
  offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(10L)));

  final List<String> expiredKeys = new ArrayList<>();
  offHeapStore.getStoreEventSource().addEventListener(event -> {
    if (event.getType() == EventType.EXPIRED) {
      expiredKeys.add(event.getKey());
    }
  });

  offHeapStore.put("key1", "value1");
  offHeapStore.put("key2", "value2");

  offHeapStore.get("key1");   // Bring the entry to the caching tier

  timeSource.advanceTime(11);   // Expire the elements

  offHeapStore.get("key1");
  offHeapStore.get("key2");
  assertThat(expiredKeys, containsInAnyOrder("key1", "key2"));
  assertThat(getExpirationStatistic(offHeapStore).count(StoreOperationOutcomes.ExpirationOutcome.SUCCESS), is(2L));
}
 
Example #14
Source File: StoreGetAndComputeTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@SPITest
public void testComputeExpiresOnUpdate() throws Exception {
  TestTimeSource timeSource = new TestTimeSource(10042L);
  kvStore = factory.newStoreWithExpiry(ExpiryPolicyBuilder.expiry().update(Duration.ZERO).build(), timeSource);

  final K key = factory.createKey(1042L);
  final V value = factory.createValue(1340142L);
  final V newValue = factory.createValue(134054142L);

  try {
    kvStore.put(key, value);

    Store.ValueHolder<V> result = kvStore.getAndCompute(key, (k, v) -> newValue);
    assertThat(result.get(), is(value));
    assertThat(kvStore.get(key), nullValue());
  } catch (StoreAccessException e) {
    throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test");
  }
}
 
Example #15
Source File: AbstractChainResolverTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCompactingTwoKeys() {
  ServerStoreProxy.ChainEntry chain = getEntryFromOperations(
    new PutOperation<>(1L, "Albin", 0L),
    new PutOperation<>(2L, "Albin", 0L),
    new PutOperation<>(1L, "Suresh", 0L),
    new PutOperation<>(2L, "Suresh", 0L),
    new PutOperation<>(2L, "Matthew", 0L));

  ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration());

  resolver.compact(chain);

  verify(chain).replaceAtHead(argThat(containsInAnyOrder( //@SuppressWarnings("unchecked")
    operation(new PutOperation<>(2L, "Matthew", 0L)),
    operation(new PutOperation<>(1L, "Suresh", 0L))
  )));
}
 
Example #16
Source File: TierCalculationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws Exception {
  CacheConfiguration<Integer, String> cacheConfiguration =
    CacheConfigurationBuilder
      .newCacheConfigurationBuilder(Integer.class, String.class, resources)
      .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION)))
      .withService(new StoreStatisticsConfiguration(true)) // explicitly enable statistics
      .build();

  StatisticsService statisticsService = new DefaultStatisticsService();

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("cache", cacheConfiguration)
    .using(new DefaultPersistenceConfiguration(diskPath.newFolder()))
    .using(statisticsService)
    .using(new TimeSourceConfiguration(timeSource))
    .build(true);

  cache = cacheManager.getCache("cache", Integer.class, String.class);

  // Get the tier statistic.
  tierStatistics = statisticsService.getCacheStatistics("cache")
    .getTierStatistics().get(tierName);
}
 
Example #17
Source File: CoreCacheConfigurationParser.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked", "deprecation"})
private static ExpiryPolicy<? super Object, ? super Object> getExpiry(ClassLoader cacheClassLoader, Expiry parsedExpiry)
  throws ClassNotFoundException, InstantiationException, IllegalAccessException {
  if (parsedExpiry.isUserDef()) {
    try {
      return getInstanceOfName(parsedExpiry.type(), cacheClassLoader, ExpiryPolicy.class);
    } catch (ClassCastException e) {
      return ExpiryUtils.convertToExpiryPolicy(getInstanceOfName(parsedExpiry.type(), cacheClassLoader, org.ehcache.expiry.Expiry.class));
    }
  } else if (parsedExpiry.isTTL()) {
    return ExpiryPolicyBuilder.timeToLiveExpiration(Duration.of(parsedExpiry.value(), parsedExpiry.unit()));
  } else if (parsedExpiry.isTTI()) {
    return ExpiryPolicyBuilder.timeToIdleExpiration(Duration.of(parsedExpiry.value(), parsedExpiry.unit()));
  } else {
    return ExpiryPolicyBuilder.noExpiration();
  }
}
 
Example #18
Source File: CoreCacheConfigurationParser.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
public CacheType unparseConfiguration(CacheConfiguration<?, ?> cacheConfiguration, CacheType cacheType) {
  ExpiryPolicy<?, ?> expiryPolicy = cacheConfiguration.getExpiryPolicy();
  if (expiryPolicy != null) {
    Duration expiry = expiryPolicy.getExpiryForCreation(null, null);
    ExpiryType expiryType = new ExpiryType();
    if (expiryPolicy.equals(ExpiryPolicy.NO_EXPIRY)) {
      expiryType.withNone(new ExpiryType.None());
    } else if (expiryPolicy.equals(ExpiryPolicyBuilder.timeToLiveExpiration(expiry))) {
      expiryType.withTtl(convertToTimeType(expiry));
    } else if (expiryPolicy.equals(ExpiryPolicyBuilder.timeToIdleExpiration(expiry))) {
      expiryType.withTti(convertToTimeType(expiry));
    } else {
      throw new XmlConfigurationException("XML translation of custom expiry policy is not supported");
    }
    cacheType.withExpiry(expiryType);
  }

  EvictionAdvisor<?, ?> evictionAdvisor = cacheConfiguration.getEvictionAdvisor();
  if (evictionAdvisor != null) {
    throw new XmlConfigurationException("XML translation of eviction advisor is not supported");
  }

  return cacheType;
}
 
Example #19
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testXmlToString() throws IOException {
  // tag::xmlTranslation[]
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .with(CacheManagerBuilder.persistence(tmpDir.newFile("myData")))
    .withCache("threeTieredCache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
        ResourcePoolsBuilder.newResourcePoolsBuilder()
          .heap(10, EntryUnit.ENTRIES)
          .offheap(1, MemoryUnit.MB)
          .disk(20, MemoryUnit.MB, true))
        .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(20)))
    ).build(false);

  Configuration configuration = cacheManager.getRuntimeConfiguration();
  XmlConfiguration xmlConfiguration = new XmlConfiguration(configuration);  // <1>
  String xml = xmlConfiguration.toString(); // <2>
  // end::xmlTranslation[]
}
 
Example #20
Source File: ExpiryChainResolverTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test @Override
public void testCompactDecodesOperationValueOnlyOnDemand() {
  ServerStoreProxy.ChainEntry chain = getEntryFromOperations(
    new PutOperation<>(1L, "Albin", 1),
    new PutOperation<>(1L, "Suresh", 2),
    new PutOperation<>(1L, "Matthew", 3));

  CountingLongSerializer keySerializer = new CountingLongSerializer();
  CountingStringSerializer valueSerializer = new CountingStringSerializer();
  OperationsCodec<Long, String> customCodec = new OperationsCodec<>(keySerializer, valueSerializer);
  ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration(), customCodec);
  resolver.compact(chain);

  assertThat(keySerializer.decodeCount, is(3));
  assertThat(valueSerializer.decodeCount, is(3));
  assertThat(valueSerializer.encodeCount, is(0));
  assertThat(keySerializer.encodeCount, is(1)); //One encode from encoding the resolved operation's key
}
 
Example #21
Source File: AbstractChainResolverTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompactSinglePutIfAbsent() {
  ServerStoreProxy.ChainEntry chain = getEntryFromOperations(new PutIfAbsentOperation<>(1L, "Matthew", 0L));

  ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration());
  resolver.compact(chain);
  verify(chain, never()).replaceAtHead(any());
}
 
Example #22
Source File: AbstractChainResolverTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFullResolveMultiplePuts() {
  Chain chain = getEntryFromOperations(
    new PutOperation<>(1L, "Albin", 0L),
    new PutOperation<>(1L, "Suresh", 0L),
    new PutOperation<>(1L, "Matthew", 0L));

  ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration());
  Map<Long, Store.ValueHolder<String>> resolved = resolver.resolveAll(chain, 0L);
  assertThat(resolved.get(1L).get(), is("Matthew"));
}
 
Example #23
Source File: AbstractOffHeapStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testEvictionAdvisor() throws StoreAccessException {
  ExpiryPolicy<Object, Object> expiry = ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L));
  EvictionAdvisor<String, byte[]> evictionAdvisor = (key, value) -> true;

  performEvictionTest(timeSource, expiry, evictionAdvisor);
}
 
Example #24
Source File: AbstractChainResolverTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testResolveChainWithNonExistentKey() {
  ServerStoreProxy.ChainEntry chain = getEntryFromOperations(
    new PutOperation<>(1L, "Albin", 0L),
    new PutOperation<>(2L, "Suresh", 0L),
    new PutOperation<>(2L, "Matthew", 0L));

  ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration());
  Store.ValueHolder<String> valueHolder = resolver.resolve(chain, 3L, 0L);
  assertThat(valueHolder, nullValue());
  verify(chain, never()).replaceAtHead(any());
}
 
Example #25
Source File: BaseOnHeapStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetOfComputeIfAbsentExpiresWithLoaderWriter() throws Exception {
  TestTimeSource timeSource = new TestTimeSource();
  OnHeapStore<String, String> store = newStore(timeSource,
    ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1)));
  @SuppressWarnings("unchecked")
  CachingTier.InvalidationListener<String, String> invalidationListener = mock(CachingTier.InvalidationListener.class);
  store.setInvalidationListener(invalidationListener);

  // Add an entry
  store.put("key", "value");
  assertThat(storeSize(store), is(1));

  // Advance after expiration time
  timeSource.advanceTime(1);

  @SuppressWarnings("unchecked")
  final ValueHolder<String> vh = mock(ValueHolder.class);
  when(vh.get()).thenReturn("newvalue");
  when(vh.expirationTime()).thenReturn(2L);

  ValueHolder<String> newValue = store.getOrComputeIfAbsent("key", s -> vh);

  assertThat(newValue, valueHeld("newvalue"));
  assertThat(store.get("key"), valueHeld("newvalue"));
  verify(invalidationListener).onInvalidation(eq("key"), argThat(valueHeld("value")));
  assertThat(storeSize(store), is(1));
  StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.ExpirationOutcome.SUCCESS));
}
 
Example #26
Source File: AbstractChainResolverTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testResolveForSingleOperationDoesNotCompact() {
  ServerStoreProxy.ChainEntry chain = getEntryFromOperations(new PutOperation<>(1L, "Albin", 0L));

  ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration());
  Store.ValueHolder<String> valueHolder = resolver.resolve(chain, 1L, 0L);
  assertThat(valueHolder.get(), is("Albin"));
  verify(chain, never()).replaceAtHead(any());
}
 
Example #27
Source File: OnHeapStoreBulkMethodsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected <K, V> Store.Configuration<K, V> mockStoreConfig() {
  @SuppressWarnings("rawtypes")
  Store.Configuration config = mock(Store.Configuration.class);
  when(config.getExpiry()).thenReturn(ExpiryPolicyBuilder.noExpiration());
  when(config.getKeyType()).thenReturn(Number.class);
  when(config.getValueType()).thenReturn(CharSequence.class);
  when(config.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(Long.MAX_VALUE, EntryUnit.ENTRIES).build());
  return config;
}
 
Example #28
Source File: AbstractOffHeapStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAndRemoveValue() throws Exception {
  offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.noExpiration());

  offHeapStore.put("1", "one");
  assertThat(offHeapStore.getAndRemove("1").get(), equalTo("one"));
  validateStats(offHeapStore, EnumSet.of(LowerCachingTierOperationsOutcome.GetAndRemoveOutcome.HIT_REMOVED));
  assertThat(offHeapStore.get("1"), is(nullValue()));
}
 
Example #29
Source File: CoreCacheConfigurationParserTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void unparseConfigurationTtiExpiry() {
  CacheConfiguration<Object, Object> cacheConfiguration = buildCacheConfigWith(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(2500)));
  CacheType cacheType = parser.unparseConfiguration(cacheConfiguration, new CacheType());
  TimeType tti = cacheType.getExpiry().getTti();
  assertThat(tti, notNullValue());
  assertThat(tti.getValue(), is(BigInteger.valueOf(2500)));
  assertThat(tti.getUnit(), is(TimeUnit.MILLIS));
}
 
Example #30
Source File: EventsFailureBehaviorTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testEventsFailover() throws Exception {
  AccountingCacheEventListener<Long, byte[]> accountingCacheEventListener1 = new AccountingCacheEventListener<>();
  Cache<Long, byte[]> cache1 = createCache(cacheManager1, accountingCacheEventListener1, ExpiryPolicyBuilder.noExpiration());
  AccountingCacheEventListener<Long, byte[]> accountingCacheEventListener2 = new AccountingCacheEventListener<>();
  Cache<Long, byte[]> cache2 = createCache(cacheManager2, accountingCacheEventListener2, ExpiryPolicyBuilder.noExpiration());


  byte[] value = new byte[10 * 1024];

  range(0, KEYS).forEach(k -> {
    cache1.put(k, value);
  });
  assertThat(() -> accountingCacheEventListener1.events.get(EventType.CREATED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener1.events.get(EventType.EVICTED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener2.events.get(EventType.CREATED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener2.events.get(EventType.EVICTED), within(TIMEOUT).matches(hasSize(greaterThan(0))));

  // failover passive -> active
  failover(cache1, cache2);

  range(0, KEYS).forEach(k -> {
    cache1.put(k, value);
  });
  assertThat(() -> accountingCacheEventListener1.events.get(EventType.UPDATED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener2.events.get(EventType.UPDATED), within(TIMEOUT).matches(hasSize(greaterThan(0))));

  range(0, KEYS).forEach(cache1::remove);
  assertThat(() -> accountingCacheEventListener1.events.get(EventType.REMOVED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener2.events.get(EventType.REMOVED), within(TIMEOUT).matches(hasSize(greaterThan(0))));

  range(KEYS, KEYS * 2).forEach(k -> {
    cache1.put(k, value);
  });
  assertThat(() -> accountingCacheEventListener1.events.get(EventType.CREATED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener1.events.get(EventType.EVICTED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener2.events.get(EventType.CREATED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener2.events.get(EventType.EVICTED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
}