org.ehcache.expiry.ExpiryPolicy Java Examples

The following examples show how to use org.ehcache.expiry.ExpiryPolicy. 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: EhcacheBase.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
protected static <K, V> boolean newValueAlreadyExpired(Logger logger, ExpiryPolicy<? super K, ? super V> expiry, K key, V oldValue, V newValue) {
  if (newValue == null) {
    return false;
  }

  Duration duration;
  try {
    if (oldValue == null) {
      duration = expiry.getExpiryForCreation(key, newValue);
    } else {
      duration = expiry.getExpiryForUpdate(key, () -> oldValue, newValue);
    }
  } catch (RuntimeException re) {
    logger.error("Expiry computation caused an exception - Expiry duration will be 0 ", re);
    return true;
  }

  return Duration.ZERO.equals(duration);
}
 
Example #2
Source File: OffHeapStoreTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Override
protected OffHeapStore<String, byte[]> createAndInitStore(TimeSource timeSource, ExpiryPolicy<? super String, ? super byte[]> expiry, EvictionAdvisor<? super String, ? super byte[]> evictionAdvisor) {
  try {
    SerializationProvider serializationProvider = new DefaultSerializationProvider(null);
    serializationProvider.start(providerContaining());
    ClassLoader classLoader = getClass().getClassLoader();
    Serializer<String> keySerializer = serializationProvider.createValueSerializer(String.class, classLoader);
    Serializer<byte[]> valueSerializer = serializationProvider.createValueSerializer(byte[].class, classLoader);
    StoreConfigurationImpl<String, byte[]> storeConfiguration = new StoreConfigurationImpl<>(String.class, byte[].class,
      evictionAdvisor, getClass().getClassLoader(), expiry, null, 0, keySerializer, valueSerializer);
    OffHeapStore<String, byte[]> offHeapStore = new OffHeapStore<String, byte[]>(storeConfiguration, timeSource, new TestStoreEventDispatcher<>(), MemoryUnit.MB
      .toBytes(1), new DefaultStatisticsService()) {
      @Override
      protected OffHeapValueHolderPortability<byte[]> createValuePortability(Serializer<byte[]> serializer) {
        return new AssertingOffHeapValueHolderPortability<>(serializer);
      }
    };
    OffHeapStore.Provider.init(offHeapStore);
    return offHeapStore;
  } catch (UnsupportedTypeException e) {
    throw new AssertionError(e);
  }
}
 
Example #3
Source File: OffHeapStoreTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Override
protected OffHeapStore<String, String> createAndInitStore(TimeSource timeSource, ExpiryPolicy<? super String, ? super String> expiry) {
  try {
    SerializationProvider serializationProvider = new DefaultSerializationProvider(null);
    serializationProvider.start(providerContaining());
    ClassLoader classLoader = getClass().getClassLoader();
    Serializer<String> keySerializer = serializationProvider.createKeySerializer(String.class, classLoader);
    Serializer<String> valueSerializer = serializationProvider.createValueSerializer(String.class, classLoader);
    StoreConfigurationImpl<String, String> storeConfiguration = new StoreConfigurationImpl<>(String.class, String.class,
      null, classLoader, expiry, null, 0, keySerializer, valueSerializer);
    OffHeapStore<String, String> offHeapStore = new OffHeapStore<String, String>(storeConfiguration, timeSource, new TestStoreEventDispatcher<>(), MemoryUnit.MB
      .toBytes(1), new DefaultStatisticsService()) {
      @Override
      protected OffHeapValueHolderPortability<String> createValuePortability(Serializer<String> serializer) {
        return new AssertingOffHeapValueHolderPortability<>(serializer);
      }
    };
    OffHeapStore.Provider.init(offHeapStore);
    return offHeapStore;
  } catch (UnsupportedTypeException e) {
    throw new AssertionError(e);
  }
}
 
Example #4
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 #5
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 #6
Source File: AbstractOffHeapStoreTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
private void performEvictionTest(TestTimeSource timeSource, ExpiryPolicy<Object, Object> expiry, EvictionAdvisor<String, byte[]> evictionAdvisor) throws StoreAccessException {
  AbstractOffHeapStore<String, byte[]> offHeapStore = createAndInitStore(timeSource, expiry, evictionAdvisor);
  try {
    @SuppressWarnings("unchecked")
    StoreEventListener<String, byte[]> listener = mock(StoreEventListener.class);
    offHeapStore.getStoreEventSource().addEventListener(listener);

    byte[] value = getBytes(MemoryUnit.KB.toBytes(200));
    offHeapStore.put("key1", value);
    offHeapStore.put("key2", value);
    offHeapStore.put("key3", value);
    offHeapStore.put("key4", value);
    offHeapStore.put("key5", value);
    offHeapStore.put("key6", value);

    Matcher<StoreEvent<String, byte[]>> matcher = eventType(EventType.EVICTED);
    verify(listener, atLeast(1)).onEvent(argThat(matcher));
  } finally {
    destroyStore(offHeapStore);
  }
}
 
Example #7
Source File: StoreConfigurationImpl.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@code StoreConfigurationImpl} based on the provided parameters.
 *
 * @param keyType the key type
 * @param valueType the value type
 * @param evictionAdvisor the eviction advisor
 * @param classLoader the class loader
 * @param expiry the expiry policy
 * @param resourcePools the resource pools
 * @param dispatcherConcurrency the level of concurrency for ordered events
 * @param operationStatisticsEnabled if operation statistics should be enabled
 * @param keySerializer the key serializer
 * @param valueSerializer the value serializer
 * @param cacheLoaderWriter the loader-writer
 */
public StoreConfigurationImpl(Class<K> keyType, Class<V> valueType,
                              EvictionAdvisor<? super K, ? super V> evictionAdvisor,
                              ClassLoader classLoader, ExpiryPolicy<? super K, ? super V> expiry,
                              ResourcePools resourcePools, int dispatcherConcurrency, boolean operationStatisticsEnabled,
                              Serializer<K> keySerializer, Serializer<V> valueSerializer,
                              CacheLoaderWriter<? super K, V> cacheLoaderWriter, boolean useLoaderInAtomics) {
  this.keyType = keyType;
  this.valueType = valueType;
  this.evictionAdvisor = evictionAdvisor;
  this.classLoader = classLoader;
  this.expiry = expiry;
  this.resourcePools = resourcePools;
  this.keySerializer = keySerializer;
  this.valueSerializer = valueSerializer;
  this.dispatcherConcurrency = dispatcherConcurrency;
  this.operationStatisticsEnabled = operationStatisticsEnabled;
  this.cacheLoaderWriter = cacheLoaderWriter;
  this.useLoaderInAtomics = useLoaderInAtomics;

}
 
Example #8
Source File: BaseCacheConfiguration.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@code BaseCacheConfiguration} from the given parameters.
 *
 * @param keyType the key type
 * @param valueType the value type
 * @param evictionAdvisor the eviction advisor
 * @param classLoader the class loader
 * @param expiry the expiry policy
 * @param resourcePools the resource pools
 * @param serviceConfigurations the service configurations
 */
public BaseCacheConfiguration(Class<K> keyType, Class<V> valueType,
        EvictionAdvisor<? super K, ? super V> evictionAdvisor,
        ClassLoader classLoader, ExpiryPolicy<? super K, ? super V> expiry,
        ResourcePools resourcePools, ServiceConfiguration<?, ?>... serviceConfigurations) {
  if (keyType == null) {
    throw new NullPointerException("keyType cannot be null");
  }
  if (valueType == null) {
    throw new NullPointerException("valueType cannot be null");
  }
  if (resourcePools == null) {
    throw new NullPointerException("resourcePools cannot be null");
  }
  this.keyType = keyType;
  this.valueType = valueType;
  this.evictionAdvisor = evictionAdvisor;
  this.classLoader = classLoader;
  if (expiry != null) {
    this.expiry = expiry;
  } else {
    this.expiry = ExpiryPolicy.NO_EXPIRY;
  }
  this.resourcePools = resourcePools;
  this.serviceConfigurations = Collections.unmodifiableCollection(Arrays.asList(serviceConfigurations));
}
 
Example #9
Source File: ExpiryChainResolverTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testGetExpiryForCreationIsInvokedOnlyOnce() {
  TimeSource timeSource = new TestTimeSource();
  ExpiryPolicy<Long, String> expiry = mock(ExpiryPolicy.class);
  ChainResolver<Long, String> chainResolver = createChainResolver(expiry);

  when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(ExpiryPolicy.INFINITE);

  ServerStoreProxy.ChainEntry chain = getEntryFromOperations(
    new PutOperation<>(1L, "One", timeSource.getTimeMillis()),
    new PutOperation<>(1L, "Second", timeSource.getTimeMillis()),
    new PutOperation<>(1L, "Three", timeSource.getTimeMillis()),
    new PutOperation<>(1L, "Four", timeSource.getTimeMillis())
  );

  Store.ValueHolder<String> valueHolder = chainResolver.resolve(chain, 1L, timeSource.getTimeMillis());

  InOrder inOrder = inOrder(expiry);

  inOrder.verify(expiry, times(1)).getExpiryForCreation(anyLong(), anyString());
  inOrder.verify(expiry, times(3)).getExpiryForUpdate(anyLong(), any(), anyString());

  verify(chain).replaceAtHead(any());
}
 
Example #10
Source File: ExpiryChainResolverTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testNullGetExpiryForUpdate() {
  TimeSource timeSource = new TestTimeSource();
  ExpiryPolicy<Long, String> expiry = mock(ExpiryPolicy.class);
  ChainResolver<Long, String> chainResolver = createChainResolver(expiry);

  when(expiry.getExpiryForUpdate(anyLong(), any(), anyString())).thenReturn(null);

  ServerStoreProxy.ChainEntry chain = getEntryFromOperations(
    new PutOperation<>(1L, "Replaced", -10L),
    new PutOperation<>(1L, "New", timeSource.getTimeMillis())
  );

  Store.ValueHolder<String> resolvedChain = chainResolver.resolve(chain, 1L, timeSource.getTimeMillis());

  assertThat(resolvedChain.get(), is("New"));

  verify(chain).replaceAtHead(argThat(contains(operation(new PutOperation<>(1L, "New", -10L)))));
}
 
Example #11
Source File: ExpiryUtils.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the expiry for creation duration returned by the provided {@link ExpiryPolicy} but checks for immediate
 * expiry, null expiry and exceptions. In all those cases, {@code null} will be returned.
 *
 * @param key key to pass to {@link ExpiryPolicy#getExpiryForCreation(Object, Object)}
 * @param value value to pass to to pass to {@link ExpiryPolicy#getExpiryForCreation(Object, Object)}
 * @param expiry expiry queried
 * @param <K> type of key
 * @param <V> type of value
 * @return the duration returned by to pass to {@link ExpiryPolicy#getExpiryForCreation(Object, Object)}, {@code null}
 * if the call throws an exception, if the returned duration is {@code null} or if it is lower or equal to 0
 */
public static <K, V> Duration getExpiryForCreation(K key, V value, ExpiryPolicy<? super K, ? super V> expiry) {
  Duration duration;
  try {
    duration = expiry.getExpiryForCreation(key, value);
  } catch (RuntimeException e) {
    LOG.error("Expiry computation caused an exception - Expiry duration will be 0", e);
    return Duration.ZERO;
  }

  if (duration == null) {
    LOG.error("Expiry for creation can't be null - Expiry duration will be 0");
    return Duration.ZERO;
  }

  if (Duration.ZERO.compareTo(duration) >= 0) {
    return Duration.ZERO;
  }

  return duration;
}
 
Example #12
Source File: ExpiryChainResolverTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testGetExpiryForUpdateUpdatesExpirationTimeStamp() {
  TimeSource timeSource = new TestTimeSource();
  ExpiryPolicy<Long, String> expiry = mock(ExpiryPolicy.class);
  ChainResolver<Long, String> chainResolver = createChainResolver(expiry);

  when(expiry.getExpiryForUpdate(anyLong(), any(), anyString())).thenReturn(ofMillis(2L));

  ServerStoreProxy.ChainEntry chain = getEntryFromOperations(
    new PutOperation<>(1L, "Replaced", -10L),
    new PutOperation<>(1L, "New", timeSource.getTimeMillis())
  );

  Store.ValueHolder<String> valueHolder = chainResolver.resolve(chain, 1L, timeSource.getTimeMillis());

  assertThat(valueHolder.get(), is("New"));
  verify(chain).replaceAtHead(argThat(contains(operation(new PutOperation<>(1L, "New", -2L)))));
}
 
Example #13
Source File: ExpiryPolicyBuilderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpirationFunctions() {
  Duration creation = Duration.ofSeconds(1L);
  Duration access = Duration.ofSeconds(2L);
  Duration update = Duration.ofSeconds(3L);
  ExpiryPolicy<Object, Object> expiry = ExpiryPolicyBuilder.expiry()
    .create((k, v) -> {
      assertThat(k, equalTo(10L));
      assertThat(v, equalTo(20L));
      return creation;
    })
    .access((k, v) -> {
      assertThat(k, equalTo(10L));
      assertThat(v.get(), equalTo(20L));
      return access;
    })
    .update((k, v1, v2) -> {
      assertThat(k, equalTo(10L));
      assertThat(v1.get(), equalTo(20L));
      assertThat(v2, equalTo(30L));
      return update;
    })
    .build();
  assertThat(expiry.getExpiryForCreation(10L, 20L), equalTo(creation));
  assertThat(expiry.getExpiryForAccess(10L, () -> 20L), equalTo(access));
  assertThat(expiry.getExpiryForUpdate(10L, () -> 20L,30L), equalTo(update));
}
 
Example #14
Source File: OnHeapStoreByValueTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
protected <K, V> OnHeapStore<K, V> newStore(TimeSource timeSource, ExpiryPolicy<? super K, ? super V> expiry,
    EvictionAdvisor<? super K, ? super V> evictionAdvisor) {
  Copier<K> keyCopier = new SerializingCopier<>(new JavaSerializer<>(getClass().getClassLoader()));
  Copier<V> valueCopier = new SerializingCopier<>(new JavaSerializer<>(getClass().getClassLoader()));
  return newStore(timeSource, expiry, evictionAdvisor, keyCopier, valueCopier, 100);
}
 
Example #15
Source File: ExpiryPolicyBuilderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpiration() {
  Duration creation = Duration.ofSeconds(1L);
  Duration access = Duration.ofSeconds(2L);
  Duration update = Duration.ofSeconds(3L);
  ExpiryPolicy<Object, Object> expiry = ExpiryPolicyBuilder.expiry().create(creation).access(access).update(update).build();
  assertThat(expiry.getExpiryForCreation(this, this), equalTo(creation));
  assertThat(expiry.getExpiryForAccess(this, () -> this), equalTo(access));
  assertThat(expiry.getExpiryForUpdate(this, () -> this,this), equalTo(update));
}
 
Example #16
Source File: ExpiryPolicyBuilderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testTTLExpiration() {
  java.time.Duration duration = java.time.Duration.ofSeconds(1L);
  ExpiryPolicy<Object, Object> expiry = ExpiryPolicyBuilder.timeToLiveExpiration(duration);
  assertThat(expiry.getExpiryForCreation(this, this), equalTo(duration));
  assertThat(expiry.getExpiryForAccess(this, () -> this), nullValue());
  assertThat(expiry.getExpiryForUpdate(this, () -> this, this), equalTo(duration));

  ExpiryPolicy<Object, Object> otherExpiry = ExpiryPolicyBuilder.timeToLiveExpiration(java.time.Duration.ofSeconds(1L));
  assertThat(otherExpiry, equalTo(expiry));
}
 
Example #17
Source File: ExpiryPolicyBuilderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testTTIExpiration() {
  java.time.Duration duration = java.time.Duration.ofSeconds(1L);
  ExpiryPolicy<Object, Object> expiry = ExpiryPolicyBuilder.timeToIdleExpiration(duration);
  assertThat(expiry.getExpiryForCreation(this, this), equalTo(duration));
  assertThat(expiry.getExpiryForAccess(this, () -> this), equalTo(duration));
  assertThat(expiry.getExpiryForUpdate(this, () -> this, this), equalTo(duration));

  ExpiryPolicy<Object, Object> otherExpiry = ExpiryPolicyBuilder.timeToIdleExpiration(java.time.Duration.ofSeconds(1L));
  assertThat(otherExpiry, equalTo(expiry));
}
 
Example #18
Source File: ExpiryPolicyBuilderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoExpiration() {
  ExpiryPolicy<Object, Object> expiry = ExpiryPolicyBuilder.noExpiration();
  assertThat(expiry, sameInstance(ExpiryPolicy.NO_EXPIRY));
  assertThat(expiry.getExpiryForCreation(this, this), equalTo(ExpiryPolicy.INFINITE));
  assertThat(expiry.getExpiryForAccess(this, () -> this), nullValue());
  assertThat(expiry.getExpiryForUpdate(this, () -> this, this), nullValue());
}
 
Example #19
Source File: ExpiryPolicyBuilder.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * Get a time-to-idle (TTI) {@link ExpiryPolicy} instance for the given {@link Duration}.
 *
 * @param timeToIdle the TTI duration
 * @return a TTI expiry
 */
public static ExpiryPolicy<Object, Object> timeToIdleExpiration(Duration timeToIdle) {
  Objects.requireNonNull(timeToIdle, "TTI duration cannot be null");
  if (timeToIdle.isNegative()) {
    throw new IllegalArgumentException("TTI duration cannot be negative");
  }
  return new TimeToIdleExpiryPolicy(timeToIdle);
}
 
Example #20
Source File: XmlConfigurationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpiryIsParsed() throws Exception {
  URL resource = XmlConfigurationTest.class.getResource("/configs/expiry-caches.xml");
  final XmlConfiguration xmlConfiguration = new XmlConfiguration(resource);

  ExpiryPolicy<?, ?> expiry = xmlConfiguration.getCacheConfigurations().get("none").getExpiryPolicy();
  ExpiryPolicy<?, ?> value = ExpiryPolicyBuilder.noExpiration();
  assertThat(expiry, is(value));

  expiry = xmlConfiguration.getCacheConfigurations().get("notSet").getExpiryPolicy();
  value = ExpiryPolicyBuilder.noExpiration();
  assertThat(expiry, is(value));

  expiry = xmlConfiguration.getCacheConfigurations().get("class").getExpiryPolicy();
  assertThat(expiry, CoreMatchers.instanceOf(com.pany.ehcache.MyExpiry.class));

  expiry = xmlConfiguration.getCacheConfigurations().get("deprecatedClass").getExpiryPolicy();
  assertThat(expiry.getExpiryForCreation(null, null), is(Duration.ofSeconds(42)));
  assertThat(expiry.getExpiryForAccess(null, () -> null), is(Duration.ofSeconds(42)));
  assertThat(expiry.getExpiryForUpdate(null, () -> null, null), is(Duration.ofSeconds(42)));

  expiry = xmlConfiguration.getCacheConfigurations().get("tti").getExpiryPolicy();
  value = ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(500));
  assertThat(expiry, equalTo(value));

  expiry = xmlConfiguration.getCacheConfigurations().get("ttl").getExpiryPolicy();
  value = ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(30));
  assertThat(expiry, equalTo(value));
}
 
Example #21
Source File: CacheConfigurationBuilderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testNothing() {
  final CacheConfigurationBuilder<Long, CharSequence> builder = newCacheConfigurationBuilder(Long.class, CharSequence.class, heap(10));

  final ExpiryPolicy<Object, Object> expiry = ExpiryPolicyBuilder.timeToIdleExpiration(ExpiryPolicy.INFINITE);

  builder
      .withEvictionAdvisor((key, value) -> value.charAt(0) == 'A')
      .withExpiry(expiry)
      .build();
}
 
Example #22
Source File: CacheConfigurationBuilderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testOffheapGetsAddedToCacheConfiguration() {
  CacheConfigurationBuilder<Long, CharSequence> builder = newCacheConfigurationBuilder(Long.class, CharSequence.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES)
          .offheap(10, MemoryUnit.MB));

  final ExpiryPolicy<Object, Object> expiry = ExpiryPolicyBuilder.timeToIdleExpiration(ExpiryPolicy.INFINITE);

  CacheConfiguration<Long, CharSequence> config = builder
      .withEvictionAdvisor((key, value) -> value.charAt(0) == 'A')
      .withExpiry(expiry)
      .build();
  assertThat(config.getResourcePools().getPoolForResource(ResourceType.Core.OFFHEAP).getType(), Matchers.is(ResourceType.Core.OFFHEAP));
  assertThat(config.getResourcePools().getPoolForResource(ResourceType.Core.OFFHEAP).getUnit(), Matchers.is(MemoryUnit.MB));
}
 
Example #23
Source File: EhcacheBulkMethodsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
protected InternalCache<Number, CharSequence> getCache(Store<Number, CharSequence> store) {
  CacheConfiguration<Number, CharSequence> cacheConfig = mock(CacheConfiguration.class);
  when(cacheConfig.getExpiryPolicy()).thenReturn(mock(ExpiryPolicy.class));
  CacheEventDispatcher<Number, CharSequence> cacheEventDispatcher = mock(CacheEventDispatcher.class);
  ResilienceStrategy<Number, CharSequence> resilienceStrategy = mock(ResilienceStrategy.class);
  return new Ehcache<>(cacheConfig, store, resilienceStrategy, cacheEventDispatcher, LoggerFactory.getLogger(Ehcache.class + "-" + "EhcacheBulkMethodsTest"));
}
 
Example #24
Source File: CacheConfigurationBuilderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCopyingOfExistingConfiguration() {
  Class<Integer> keyClass = Integer.class;
  Class<String> valueClass = String.class;
  ClassLoader loader = mock(ClassLoader.class);
  @SuppressWarnings("unchecked")
  EvictionAdvisor<Integer, String> eviction = mock(EvictionAdvisor.class);
  @SuppressWarnings("unchecked")
  ExpiryPolicy<Integer, String> expiry = mock(ExpiryPolicy.class);
  ServiceConfiguration<?, ?> service = mock(ServiceConfiguration.class);

  CacheConfiguration<Integer, String> configuration = newCacheConfigurationBuilder(Integer.class, String.class, heap(10))
    .withClassLoader(loader)
    .withEvictionAdvisor(eviction)
    .withExpiry(expiry)
    .withService(service)
    .build();

  CacheConfiguration<Integer, String> copy = newCacheConfigurationBuilder(configuration).build();

  assertThat(copy.getKeyType(), equalTo(keyClass));
  assertThat(copy.getValueType(), equalTo(valueClass));
  assertThat(copy.getClassLoader(), equalTo(loader));

  assertThat(copy.getEvictionAdvisor(), IsSame.sameInstance(eviction));
  assertThat(copy.getExpiryPolicy(), IsSame.sameInstance(expiry));
  assertThat(copy.getServiceConfigurations(), contains(IsSame.sameInstance(service)));
}
 
Example #25
Source File: OnHeapStrategyTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void setAccessTimeAndExpiryThenReturnMappingOutsideLock_nullExpiryForAccess() {
  strategy = OnHeapStrategy.strategy(store, ExpiryPolicy.NO_EXPIRY, timeSource);

  TestOnHeapValueHolder mapping = new TestOnHeapValueHolder(10);
  when(policy.getExpiryForAccess(1, mapping)).thenReturn(null);

  strategy.setAccessAndExpiryTimeWhenCallerOutsideLock(1, mapping, timeSource.getTimeMillis());

  assertThat(mapping.expiration).isNull();
  assertThat(mapping.now).isEqualTo(timeSource.getTimeMillis());

  verifyZeroInteractions(store);
}
 
Example #26
Source File: OnHeapStrategyTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void setAccessTimeAndExpiryThenReturnMappingOutsideLock_infiniteExpiryOnAccess() {
  strategy = OnHeapStrategy.strategy(store, policy, timeSource);

  TestOnHeapValueHolder mapping = new TestOnHeapValueHolder(10);
  when(policy.getExpiryForAccess(1, mapping)).thenReturn(ExpiryPolicy.INFINITE);

  strategy.setAccessAndExpiryTimeWhenCallerOutsideLock(1, mapping, timeSource.getTimeMillis());

  assertThat(mapping.expiration).isEqualTo(ExpiryPolicy.INFINITE);
  assertThat(mapping.now).isEqualTo(timeSource.getTimeMillis());

  verifyZeroInteractions(store);
}
 
Example #27
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 #28
Source File: AbstractOffHeapStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBrokenEvictionAdvisor() throws StoreAccessException {
  ExpiryPolicy<Object, Object> expiry = ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L));
  EvictionAdvisor<String, byte[]> evictionAdvisor = (key, value) -> {
    throw new UnsupportedOperationException("Broken advisor!");
  };

  performEvictionTest(timeSource, expiry, evictionAdvisor);
}
 
Example #29
Source File: ClusteredCacheExpirationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private CacheManagerBuilder<PersistentCacheManager> cacheManagerBuilder(ExpiryPolicy<Object, Object> expiry) {
  return newCacheManagerBuilder()
      .using(statisticsService)
      .using(new TimeSourceConfiguration(timeSource))
      .with(cluster(CLUSTER_URI).autoCreate(c -> c))
      .withCache(CLUSTERED_CACHE, newCacheConfigurationBuilder(Long.class, String.class,
          ResourcePoolsBuilder.newResourcePoolsBuilder()
              .heap(10, EntryUnit.ENTRIES)
              .offheap(6, MemoryUnit.MB)
              .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 8, MemoryUnit.MB)))
            .withExpiry(expiry)
          .withService(ClusteredStoreConfigurationBuilder.withConsistency(Consistency.STRONG)));
}
 
Example #30
Source File: OffHeapDiskStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
protected OffHeapDiskStore<String, byte[]> createAndInitStore(TimeSource timeSource, ExpiryPolicy<? super String, ? super byte[]> expiry, EvictionAdvisor<? super String, ? super byte[]> evictionAdvisor) {
  try {
    SerializationProvider serializationProvider = new DefaultSerializationProvider(null);
    serializationProvider.start(providerContaining(diskResourceService));
    ClassLoader classLoader = getClass().getClassLoader();
    Serializer<String> keySerializer = serializationProvider.createKeySerializer(String.class, classLoader);
    Serializer<byte[]> valueSerializer = serializationProvider.createValueSerializer(byte[].class, classLoader);
    StoreConfigurationImpl<String, byte[]> storeConfiguration = new StoreConfigurationImpl<>(String.class, byte[].class,
      evictionAdvisor, getClass().getClassLoader(), expiry, null, 0, true, keySerializer, valueSerializer, null, false);
    OffHeapDiskStore<String, byte[]> offHeapStore = new OffHeapDiskStore<String, byte[]>(
      getPersistenceContext(),
      new OnDemandExecutionService(), null, DEFAULT_WRITER_CONCURRENCY, DEFAULT_DISK_SEGMENTS,
      storeConfiguration, timeSource,
      new TestStoreEventDispatcher<>(),
      MB.toBytes(1), new DefaultStatisticsService()) {
      @Override
      protected OffHeapValueHolderPortability<byte[]> createValuePortability(Serializer<byte[]> serializer) {
        return new AssertingOffHeapValueHolderPortability<>(serializer);
      }
    };
    OffHeapDiskStore.Provider.init(offHeapStore);
    return offHeapStore;
  } catch (UnsupportedTypeException e) {
    throw new AssertionError(e);
  }
}