org.ehcache.config.ResourceType Java Examples

The following examples show how to use org.ehcache.config.ResourceType. 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: OnHeapStore.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
public <K, V> OnHeapStore<K, V> createStoreInternal(Configuration<K, V> storeConfig, StoreEventDispatcher<K, V> eventDispatcher,
                                                    ServiceConfiguration<?, ?>... serviceConfigs) {
  TimeSource timeSource = getServiceProvider().getService(TimeSourceService.class).getTimeSource();
  CopyProvider copyProvider = getServiceProvider().getService(CopyProvider.class);
  Copier<K> keyCopier  = copyProvider.createKeyCopier(storeConfig.getKeyType(), storeConfig.getKeySerializer(), serviceConfigs);
  Copier<V> valueCopier = copyProvider.createValueCopier(storeConfig.getValueType(), storeConfig.getValueSerializer(), serviceConfigs);

  List<Copier<?>> copiers = Arrays.asList(keyCopier, valueCopier);

  SizeOfEngineProvider sizeOfEngineProvider = getServiceProvider().getService(SizeOfEngineProvider.class);
  SizeOfEngine sizeOfEngine = sizeOfEngineProvider.createSizeOfEngine(
      storeConfig.getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getUnit(), serviceConfigs);
  OnHeapStore<K, V> onHeapStore = new OnHeapStore<>(storeConfig, timeSource, keyCopier, valueCopier, sizeOfEngine, eventDispatcher, ConcurrentHashMap::new, getServiceProvider().getService(StatisticsService.class));
  createdStores.put(onHeapStore, copiers);
  return onHeapStore;
}
 
Example #2
Source File: MultiGettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleRetrieval() {
  XmlMultiConfiguration multipleConfiguration = XmlMultiConfiguration
    .from(getClass().getResource("/configs/docs/multi/multiple-managers.xml"))
    .build();
  XmlMultiConfiguration variantConfiguration = XmlMultiConfiguration
    .from(getClass().getResource("/configs/docs/multi/multiple-variants.xml"))
    .build();

  //tag::multipleRetrieval[]
  Map<String, Configuration> allConfigurations = multipleConfiguration.identities().stream() // <1>
    .collect(Collectors.toMap(i -> i, i -> multipleConfiguration.configuration(i))); // <2>
  Map<String, Configuration> offheapConfigurations = variantConfiguration.identities().stream()
    .collect(Collectors.toMap(i -> i, i -> variantConfiguration.configuration(i, "offheap"))); // <3>
  //end::multipleRetrieval[]

  Assert.assertThat(resourceMap(allConfigurations), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP)))
  ));

  Assert.assertThat(resourceMap(offheapConfigurations), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP)))
  ));
}
 
Example #3
Source File: TieredStoreTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testGetAuthoritativeTierProvider() {
  TieredStore.Provider provider = new TieredStore.Provider();
  ServiceProvider<Service> serviceProvider = mock(ServiceProvider.class);
  provider.start(serviceProvider);

  AuthoritativeTier.Provider provider1 = mock(AuthoritativeTier.Provider.class);
  when(provider1.rankAuthority(any(ResourceType.class), any())).thenReturn(1);
  AuthoritativeTier.Provider provider2 = mock(AuthoritativeTier.Provider.class);
  when(provider2.rankAuthority(any(ResourceType.class), any())).thenReturn(2);

  when(serviceProvider.getServicesOfType(AuthoritativeTier.Provider.class)).thenReturn(Arrays.asList(provider1,
                                                                                                     provider2));

  assertSame(provider.getAuthoritativeTierProvider(mock(ResourceType.class), Collections.emptyList()), provider2);
}
 
Example #4
Source File: UserManagedCacheEvictionTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void test_eviction() throws Exception {
  UserManagedCache<Number, String> cache = UserManagedCacheBuilder.newUserManagedCacheBuilder(Number.class, String.class)
      .withResourcePools(newResourcePoolsBuilder().heap(1, EntryUnit.ENTRIES))
      .build(true);
  assertThat(cache.getRuntimeConfiguration().getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getSize(),
      equalTo(1L));

  // we put 3 elements, but there's only capacity for 1
  for (int i = 0; i < 3; i++) {
    cache.putIfAbsent(i, "" + i);
  }

  // we must find at most 1 non empty value
  int nullValuesFound = 0;
  for (int i = 0; i < 3; i++) {
    String retrievedValue = cache.get(i);
    if (retrievedValue == null) {
      nullValuesFound ++;
    }
  }
  assertThat("The capacity of the store is 1, and we found more than 1 non empty value in it !", nullValuesFound, is(2));
}
 
Example #5
Source File: MultiGettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleVariants() {
  //tag::multipleVariants[]
  XmlMultiConfiguration variantConfiguration = XmlMultiConfiguration
    .from(getClass().getResource("/configs/docs/multi/multiple-variants.xml"))
    .build();

  Configuration fooConfiguration = variantConfiguration.configuration("foo-manager", "offheap"); // <1>
  //end::multipleVariants[]

  Assert.assertThat(resourceMap(variantConfiguration.identities().stream().collect(
    Collectors.toMap(Function.identity(), i -> variantConfiguration.configuration(i, "offheap"))
  )), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP)))
  ));

  Assert.assertThat(resourceMap(variantConfiguration.identities().stream().collect(
    Collectors.toMap(Function.identity(), i -> variantConfiguration.configuration(i, "heap"))
  )), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP)))
  ));
}
 
Example #6
Source File: ResourcePoolsImplTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateResourceUnitFailure() {
  ResourcePools existing = resources(
    new SizedResourcePoolImpl<>(ResourceType.Core.HEAP, 20L, MemoryUnit.MB, false),
    new SizedResourcePoolImpl<>(ResourceType.Core.DISK, 200, MemoryUnit.MB, false)
  );
  ResourcePools toBeUpdated = resources(
    new SizedResourcePoolImpl<>(ResourceType.Core.HEAP, 500, EntryUnit.ENTRIES, false)
  );

  try {
    existing = existing.validateAndMerge(toBeUpdated);
    fail();
  } catch (IllegalArgumentException uoe) {
    assertThat(uoe.getMessage(), Matchers.is("ResourcePool for heap with ResourceUnit 'entries' can not replace 'MB'"));
  }
  assertThat(existing.getPoolForResource(ResourceType.Core.HEAP).getSize(), Matchers.is(20L));
  assertThat(existing.getPoolForResource(ResourceType.Core.HEAP).getUnit(), Matchers.<ResourceUnit>is(MemoryUnit.MB));
}
 
Example #7
Source File: ConfigurationDerivation.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void updateCache() {
  Configuration configuration = ConfigurationBuilder.newConfigurationBuilder()
    .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
    .build();

  //tag::updateCache[]
  Configuration withOffHeap = configuration.derive()
    .updateCache("cache", cache -> cache.updateResourcePools(
      resources -> ResourcePoolsBuilder.newResourcePoolsBuilder(resources)
        .offheap(100, MemoryUnit.MB)
        .build()))
    .build();
  //end::updateCache[]

  Assert.assertThat(configuration.getCacheConfigurations().get("cache").getResourcePools().getResourceTypeSet(), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP));
  Assert.assertThat(withOffHeap.getCacheConfigurations().get("cache").getResourcePools().getResourceTypeSet(), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP));
}
 
Example #8
Source File: EhcacheManager.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
/**
 * Perform cache closure actions specific to a cache manager implementation.
 * This method is called <i>after</i> the {@code InternalCache} instance is closed.
 *
 * @param alias the cache alias
 * @param ehcache the {@code InternalCache} instance for the cache to close
 */
protected void closeEhcache(final String alias, final InternalCache<?, ?> ehcache) {
  for (ResourceType<?> resourceType : ehcache.getRuntimeConfiguration().getResourcePools().getResourceTypeSet()) {
    if (resourceType.isPersistable()) {
      ResourcePool resourcePool = ehcache.getRuntimeConfiguration()
          .getResourcePools()
          .getPoolForResource(resourceType);
      if (!resourcePool.isPersistent()) {
        PersistableResourceService persistableResourceService = getPersistableResourceService(resourceType);
        try {
          persistableResourceService.destroy(alias);
        } catch (CachePersistenceException e) {
          LOGGER.warn("Unable to clear persistence space for cache {}", alias, e);
        }
      }
    }
  }
}
 
Example #9
Source File: DefaultDiskResourceService.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public PersistenceSpaceIdentifier<DiskResourceService> getPersistenceSpaceIdentifier(String name, CacheConfiguration<?, ?> config) throws CachePersistenceException {
  if (persistenceService == null) {
    return null;
  }
  boolean persistent = config.getResourcePools().getPoolForResource(ResourceType.Core.DISK).isPersistent();
  while (true) {
    PersistenceSpace persistenceSpace = knownPersistenceSpaces.get(name);
    if (persistenceSpace != null) {
      return persistenceSpace.identifier;
    }
    PersistenceSpace newSpace = createSpace(name, persistent);
    if (newSpace != null) {
      return newSpace.identifier;
    }
  }
}
 
Example #10
Source File: OnHeapStore.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Override
public void cacheConfigurationChange(CacheConfigurationChangeEvent event) {
  if(event.getProperty().equals(CacheConfigurationProperty.UPDATE_SIZE)) {
    ResourcePools updatedPools = (ResourcePools)event.getNewValue();
    ResourcePools configuredPools = (ResourcePools)event.getOldValue();
    if(updatedPools.getPoolForResource(ResourceType.Core.HEAP).getSize() !=
        configuredPools.getPoolForResource(ResourceType.Core.HEAP).getSize()) {
      LOG.info("Updating size to: {}", updatedPools.getPoolForResource(ResourceType.Core.HEAP).getSize());
      SizedResourcePool pool = updatedPools.getPoolForResource(ResourceType.Core.HEAP);
      if (pool.getUnit() instanceof MemoryUnit) {
        capacity = ((MemoryUnit)pool.getUnit()).toBytes(pool.getSize());
      } else {
        capacity = pool.getSize();
      }
    }
  }
}
 
Example #11
Source File: StoreSupportTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSelectStoreProvider() throws Exception {

  final TestBaseProvider expectedProvider = new PrimaryProvider1();
  Collection<TestBaseProvider> storeProviders = asList(
      new SecondaryProvider1(),
      new ZeroProvider(),
      expectedProvider
  );

  final ServiceLocator serviceLocator = dependencySet().with(storeProviders).build();
  final Store.Provider selectedProvider = StoreSupport.selectStoreProvider(serviceLocator,
      Collections.<ResourceType<?>>singleton(anyResourceType),
      Collections.<ServiceConfiguration<?, ?>>emptyList());

  assertThat(selectedProvider, is(Matchers.<Store.Provider>sameInstance(expectedProvider)));

  for (final TestBaseProvider provider : storeProviders) {
    assertThat(provider.rankAccessCount.get(), is(1));
  }
}
 
Example #12
Source File: EhcacheRuntimeConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateResources() throws Exception {
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
          .heap(10L, EntryUnit.ENTRIES).disk(10, MemoryUnit.MB).build()).build();

  try (CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .with(new CacheManagerPersistenceConfiguration(diskPath.newFolder("myData")))
      .withCache("cache", cacheConfiguration).build(true)) {

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

    ResourcePoolsBuilder poolsBuilder = ResourcePoolsBuilder.newResourcePoolsBuilder();
    poolsBuilder = poolsBuilder.heap(20L, EntryUnit.ENTRIES);
    ResourcePools pools = poolsBuilder.build();
    cache.getRuntimeConfiguration().updateResourcePools(pools);
    assertThat(cache.getRuntimeConfiguration().getResourcePools()
      .getPoolForResource(ResourceType.Core.HEAP).getSize(), is(20L));
    pools = poolsBuilder.build();
    cache.getRuntimeConfiguration().updateResourcePools(pools);
    assertThat(cache.getRuntimeConfiguration().getResourcePools()
      .getPoolForResource(ResourceType.Core.HEAP).getSize(), is(20L));
  }
}
 
Example #13
Source File: StoreSupportTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
public int rank(final Set<ResourceType<?>> resourceTypes, final Collection<ServiceConfiguration<?, ?>> serviceConfigs) {
  assertThat(resourceTypes, is(not(nullValue())));
  assertThat(serviceConfigs, is(not(nullValue())));
  rankAccessCount.incrementAndGet();

  if (resourceTypes.contains(anyResourceType)) {
    return this.rank;
  }

  return 0;
}
 
Example #14
Source File: Tiering.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void updateResourcesAtRuntime() throws InterruptedException {
  ListenerObject listener = new ListenerObject();
  CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
    .newEventListenerConfiguration(listener, EventType.EVICTED).unordered().synchronous();

  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
    ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10L, EntryUnit.ENTRIES))
    .withService(cacheEventListenerConfiguration)
    .build();

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration)
    .build(true);

  Cache<Long, String> cache = cacheManager.getCache("cache", Long.class, String.class);
  for(long i = 0; i < 20; i++ ){
    cache.put(i, "Hello World");
  }
  assertThat(listener.evicted(), is(10));

  cache.clear();
  listener.resetEvictionCount();

  // tag::updateResourcesAtRuntime[]
  ResourcePools pools = ResourcePoolsBuilder.newResourcePoolsBuilder().heap(20L, EntryUnit.ENTRIES).build(); // <1>
  cache.getRuntimeConfiguration().updateResourcePools(pools); // <2>
  assertThat(cache.getRuntimeConfiguration().getResourcePools()
    .getPoolForResource(ResourceType.Core.HEAP).getSize(), is(20L));
  // end::updateResourcesAtRuntime[]

  for(long i = 0; i < 20; i++ ){
    cache.put(i, "Hello World");
  }
  assertThat(listener.evicted(), is(0));

  cacheManager.close();
}
 
Example #15
Source File: ClusteredStoreProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRankTiered() throws Exception {
  TieredStore.Provider provider = new TieredStore.Provider();
  ServiceLocator serviceLocator = dependencySet()
    .with(provider)
    .with(new ClusteredStore.Provider())
    .with(new OnHeapStore.Provider())
    .with(new OffHeapStore.Provider())
    .with(new OffHeapDiskStore.Provider())
    .with(mock(DiskResourceService.class))
    .with(Mockito.mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS))
    .with(mock(ClusteringService.class)).build();
  serviceLocator.startAllServices();

  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.DISK);
  assertRank(provider, 2, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.HEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.OFFHEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.DISK, ResourceType.Core.HEAP);
  assertRank(provider, 3, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);

  assertRank(provider, 0, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK);
  assertRank(provider, 2, ClusteredResourceType.Types.SHARED, ResourceType.Core.HEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.SHARED, ResourceType.Core.OFFHEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.HEAP);
  assertRank(provider, 3, ClusteredResourceType.Types.SHARED, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);

  // Multiple clustered resources not currently supported
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.HEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.OFFHEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.HEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);
}
 
Example #16
Source File: PersistentUserManagedEhcache.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
void create() {
  statusTransitioner.checkMaintenance();
  try {
    if (!getRuntimeConfiguration().getResourcePools().getPoolForResource(ResourceType.Core.DISK).isPersistent()) {
      destroy();
    }
    diskPersistenceService.getPersistenceSpaceIdentifier(id, cache.getRuntimeConfiguration());
  } catch (CachePersistenceException e) {
    throw new RuntimeException("Unable to create persistence space for user managed cache " + id, e);
  }
}
 
Example #17
Source File: OffHeapStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRank() throws Exception {
  OffHeapStore.Provider provider = new OffHeapStore.Provider();

  assertRank(provider, 1, ResourceType.Core.OFFHEAP);
  assertRank(provider, 0, ResourceType.Core.DISK);
  assertRank(provider, 0, ResourceType.Core.HEAP);
  assertRank(provider, 0, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP);
  assertRank(provider, 0, ResourceType.Core.DISK, ResourceType.Core.HEAP);
  assertRank(provider, 0, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);
  assertRank(provider, 0, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);

  assertRank(provider, 0, new UnmatchedResourceType());
  assertRank(provider, 0, ResourceType.Core.OFFHEAP, new UnmatchedResourceType());
}
 
Example #18
Source File: CompoundCachingTierTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testRankCachingTier() throws Exception {
  CompoundCachingTier.Provider provider = new CompoundCachingTier.Provider();
  HashSet<ResourceType<?>> resourceTypes = new HashSet<>(EnumSet.of(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP));
  assertThat(provider.rankCachingTier(resourceTypes, EMPTY_LIST), is(2));

  resourceTypes.clear();
  resourceTypes.add(new UnmatchedResourceType());
  assertThat(provider.rankCachingTier(resourceTypes, EMPTY_LIST), is(0));
}
 
Example #19
Source File: ClusteredStore.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
public int rank(final Set<ResourceType<?>> resourceTypes, final Collection<ServiceConfiguration<?, ?>> serviceConfigs) {
  if (clusteringService == null || resourceTypes.size() > 1 || Collections.disjoint(resourceTypes, CLUSTER_RESOURCES)) {
    // A ClusteredStore requires a ClusteringService *and* ClusteredResourcePool instances
    return 0;
  }
  return 1;
}
 
Example #20
Source File: OnHeapStoreProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testRankCachingTier() throws Exception {
  OnHeapStore.Provider provider = new OnHeapStore.Provider();

  assertThat(provider.rankCachingTier(Collections.<ResourceType<?>>singleton(ResourceType.Core.HEAP), EMPTY_LIST), is(1));
  assertThat(provider.rankCachingTier(Collections.<ResourceType<?>>singleton(new UnmatchedResourceType()), EMPTY_LIST), is(0));
}
 
Example #21
Source File: ClusteredWriteBehindStore.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
public int rankAuthority(ResourceType<?> authorityResource, Collection<ServiceConfiguration<?, ?>> serviceConfigs) {
  int parentRank = super.rankAuthority(authorityResource, serviceConfigs);
  if (parentRank == 0 || serviceConfigs.stream().noneMatch(WriteBehindConfiguration.class::isInstance)) {
    return 0;
  }
  return parentRank + 1;
}
 
Example #22
Source File: EhcacheManager.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private PersistableResourceService getPersistableResourceService(ResourceType<?> resourceType) {
  Collection<PersistableResourceService> services = serviceLocator.getServicesOfType(PersistableResourceService.class);
  for (PersistableResourceService service : services) {
    if (service.handlesResourceType(resourceType)) {
      return service;
    }
  }
  throw new IllegalStateException("No service found for persistable resource: " + resourceType);
}
 
Example #23
Source File: ClusteredWriteBehindStore.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
public int rank(Set<ResourceType<?>> resourceTypes, Collection<ServiceConfiguration<?, ?>> serviceConfigs) {
  int parentRank = super.rank(resourceTypes, serviceConfigs);
  if (parentRank == 0 || serviceConfigs.stream().noneMatch(WriteBehindConfiguration.class::isInstance)) {
    return 0;
  }
  return parentRank + 1;
}
 
Example #24
Source File: ResourcePoolsImplTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddingNewTierWhileUpdating() {
  ResourcePools existing = resources(new SizedResourcePoolImpl<>(ResourceType.Core.HEAP, 10L, EntryUnit.ENTRIES, false));
  ResourcePools toBeUpdated = resources(new SizedResourcePoolImpl<>(ResourceType.Core.DISK, 10L, MemoryUnit.MB, false));
  try {
    existing.validateAndMerge(toBeUpdated);
    fail();
  } catch (IllegalArgumentException iae) {
    assertThat(iae.getMessage(), Matchers.is("Pools to be updated cannot contain previously undefined resources pools"));
  }
}
 
Example #25
Source File: TieredStore.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
public <K, V> Store<K, V> createStore(Configuration<K, V> storeConfig, ServiceConfiguration<?, ?>... serviceConfigs) {
  final List<ServiceConfiguration<?, ?>> enhancedServiceConfigs = new ArrayList<>(Arrays.asList(serviceConfigs));

  final ResourcePools resourcePools = storeConfig.getResourcePools();
  if (rank(resourcePools.getResourceTypeSet(), enhancedServiceConfigs) == 0) {
    throw new IllegalArgumentException("TieredStore.Provider does not support configured resource types "
        + resourcePools.getResourceTypeSet());
  }

  ResourceType<?> authorityResource = getAuthorityResource(resourcePools.getResourceTypeSet());
  AuthoritativeTier.Provider authoritativeTierProvider = getAuthoritativeTierProvider(authorityResource, enhancedServiceConfigs);

  Set<ResourceType<?>> cachingResources = new HashSet<>(resourcePools.getResourceTypeSet());
  cachingResources.remove(authorityResource);

  CachingTier.Provider cachingTierProvider = getCachingTierProvider(cachingResources, enhancedServiceConfigs);

  final ServiceConfiguration<?, ?>[] configurations =
      enhancedServiceConfigs.toArray(new ServiceConfiguration<?, ?>[enhancedServiceConfigs.size()]);
  CachingTier<K, V> cachingTier = cachingTierProvider.createCachingTier(storeConfig, configurations);
  AuthoritativeTier<K, V> authoritativeTier = authoritativeTierProvider.createAuthoritativeTier(storeConfig, configurations);

  TieredStore<K, V> store = new TieredStore<>(cachingTier, authoritativeTier);
  serviceProvider.getService(StatisticsService.class).registerWithParent(cachingTier, store);
  serviceProvider.getService(StatisticsService.class).registerWithParent(authoritativeTier, store);
  registerStore(store, cachingTierProvider, authoritativeTierProvider);
  return store;
}
 
Example #26
Source File: TieredStore.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private ResourceType<?> getAuthorityResource(Set<ResourceType<?>> resourceTypes) {
  ResourceType<?> authorityResource = null;
  for (ResourceType<?> resourceType : resourceTypes) {
    if (authorityResource == null || authorityResource.getTierHeight() > resourceType.getTierHeight()) {
      authorityResource = resourceType;
    }
  }
  return authorityResource;
}
 
Example #27
Source File: ClusteredLoaderWriterStore.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
public int rankAuthority(ResourceType<?> authorityResource, Collection<ServiceConfiguration<?, ?>> serviceConfigs) {
  int parentRank = super.rankAuthority(authorityResource, serviceConfigs);
  if (parentRank == 0 || serviceConfigs.stream().noneMatch(CacheLoaderWriterConfiguration.class::isInstance)) {
    return 0;
  }
  return parentRank + 1;
}
 
Example #28
Source File: StoreSupportTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSelectStoreProviderMultiple() throws Exception {

  final TestBaseProvider expectedProvider = new PrimaryProvider1();
  final Collection<TestBaseProvider> storeProviders = asList(
      new SecondaryProvider1(),
      new ZeroProvider(),
      expectedProvider,
      new SecondaryProvider2(),
      new PrimaryProvider2()
  );

  final ServiceLocator serviceLocator = dependencySet().with(storeProviders).build();

  try {
    StoreSupport.selectStoreProvider(serviceLocator,
        Collections.<ResourceType<?>>singleton(anyResourceType),
        Collections.<ServiceConfiguration<?, ?>>emptyList());
    fail();
  } catch (IllegalStateException e) {
    // expected
    assertThat(e.getMessage(), startsWith("Multiple Store.Providers "));
  }

  for (final TestBaseProvider provider : storeProviders) {
    assertThat(provider.rankAccessCount.get(), is(1));
  }
}
 
Example #29
Source File: ResourcePoolsImplTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateResourceUnitSuccess() {
  ResourcePools existing = resources(
    new SizedResourcePoolImpl<>(ResourceType.Core.HEAP, 200L, MemoryUnit.MB, false),
    new SizedResourcePoolImpl<>(ResourceType.Core.DISK, 4096L, MemoryUnit.MB, false)
  );
  ResourcePools toBeUpdated = resources(
    new SizedResourcePoolImpl<>(ResourceType.Core.HEAP, 2, MemoryUnit.GB, false)
  );

  existing = existing.validateAndMerge(toBeUpdated);
  assertThat(existing.getPoolForResource(ResourceType.Core.HEAP).getSize(), Matchers.is(2L));
  assertThat(existing.getPoolForResource(ResourceType.Core.HEAP).getUnit(), Matchers.<ResourceUnit>is(MemoryUnit.GB));
}
 
Example #30
Source File: ResourcePoolsImpl.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
public String readableString() {

  Map<ResourceType<?>, ResourcePool> sortedPools = new TreeMap<>(
    (o1, o2) -> o2.getTierHeight() - o1.getTierHeight()
  );
  sortedPools.putAll(pools);

  StringBuilder poolsToStringBuilder = new StringBuilder();

  for (Map.Entry<ResourceType<?>, ResourcePool> poolEntry : sortedPools.entrySet()) {
    poolsToStringBuilder
        .append(poolEntry.getKey())
        .append(": ")
        .append("\n        ")
        .append("size: ")
        .append(poolEntry.getValue() instanceof HumanReadable ? ((HumanReadable) poolEntry.getValue()).readableString() : poolEntry.getValue())
        .append("\n        ")
        .append("tierHeight: ")
        .append(poolEntry.getKey().getTierHeight())
        .append("\n    ");
  }

  if (poolsToStringBuilder.length() > 4) {
    poolsToStringBuilder.delete(poolsToStringBuilder.length() - 5, poolsToStringBuilder.length());
  }

  return "pools: " + "\n    " +
      poolsToStringBuilder.toString();
}