org.ehcache.config.units.MemoryUnit Java Examples

The following examples show how to use org.ehcache.config.units.MemoryUnit. 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: 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 #2
Source File: OversizedCacheOpsPassiveTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
private void doPuts(CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder,
                    CountDownLatch syncLatch) {
  try (PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) {
    CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
        .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", CACHE_SIZE_IN_MB, MemoryUnit.MB)))
      .build();

    syncLatch.countDown();
    Cache<Long, String> cache = cacheManager.createCache("clustered-cache", config);
    for (long i = 0; i < MAX_PUTS; i++) {
      if (i % 1000 == 0) {
        // a small pause
        try {
          Thread.sleep(10);
        } catch (InterruptedException e) {
          throw new AssertionError(e);
        }
      }
      cache.put(i, LARGE_VALUE);
    }
  }
}
 
Example #3
Source File: TerminatedServerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTerminationBeforeCacheManagerCloseWithCaches() throws Exception {
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
      CacheManagerBuilder.newCacheManagerBuilder()
          .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER.get().getConnectionURI().resolve("/").resolve(testName.getMethodName()))
                  .autoCreate(server -> server.defaultServerResource("primary-server-resource")))
          .withCache("simple-cache",
              CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
                  ResourcePoolsBuilder.newResourcePoolsBuilder()
                      .with(ClusteredResourcePoolBuilder.clusteredDedicated(4, MemoryUnit.MB))));
  PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false);
  cacheManager.init();

  CLUSTER.get().getClusterControl().terminateAllServers();

  cacheManager.close();

}
 
Example #4
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void explicitConsistencyConfiguration() throws Exception {
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder
          = CacheManagerBuilder.newCacheManagerBuilder()
          .with(ClusteringServiceConfigurationBuilder.cluster(URI.create("terracotta://localhost/my-application"))
                  .autoCreateOnReconnect(server -> server.defaultServerResource("primary-server-resource")
                    .resourcePool("resource-pool-a", 8, MemoryUnit.MB)));
  PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false);
  cacheManager.init();

  try {
    // tag::clusteredCacheConsistency[]
    CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
            ResourcePoolsBuilder.newResourcePoolsBuilder()
                    .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)))
        .withService(ClusteredStoreConfigurationBuilder.withConsistency(Consistency.STRONG)) // <1>
        .build();

    Cache<Long, String> cache = cacheManager.createCache("clustered-cache", config);
    cache.put(42L, "All you need to know!"); // <2>

    // end::clusteredCacheConsistency[]
  } finally {
    cacheManager.close();
  }
}
 
Example #5
Source File: CacheManagerDestroyTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testDestroyCacheManagerDoesNotAffectsExistingCacheWithExistingClientsConnected() throws CachePersistenceException {

  CacheManagerBuilder<PersistentCacheManager> cacheManagerBuilder = clusteredCacheManagerBuilder
      .withCache("test", newCacheConfigurationBuilder(Long.class, String.class,
          ResourcePoolsBuilder.newResourcePoolsBuilder()
              .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB))));

  PersistentCacheManager persistentCacheManager1 = cacheManagerBuilder.build(true);
  try (PersistentCacheManager persistentCacheManager2 = cacheManagerBuilder.build(true)) {

    persistentCacheManager1.close();
    try {
      persistentCacheManager1.destroy();
      fail("StateTransitionException expected");
    } catch (StateTransitionException e) {
      assertThat(e.getMessage(), is("Couldn't acquire cluster-wide maintenance lease"));
    }

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

    cache.put(1L, "One");

    assertThat(cache.get(1L), is("One"));
  }
}
 
Example #6
Source File: TieringTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTieredStore() throws Exception {
  CacheConfiguration<Long, String> tieredCacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).disk(10L, MemoryUnit.MB))
      .build();

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .with(new CacheManagerPersistenceConfiguration(new File(System.getProperty("java.io.tmpdir") + "/tiered-cache-data")))
      .withCache("tiered-cache", tieredCacheConfiguration).build(true);

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

  tieredCache.put(1L, "one");

  assertThat(tieredCache.get(1L), equalTo("one")); // probably coming from disk
  assertThat(tieredCache.get(1L), equalTo("one")); // probably coming from heap

  cacheManager.close();
}
 
Example #7
Source File: OffHeapStore.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
private <K, V> OffHeapStore<K, V> createStoreInternal(Configuration<K, V> storeConfig, StoreEventDispatcher<K, V> eventDispatcher, ServiceConfiguration<?, ?>... serviceConfigs) {
  if (getServiceProvider() == null) {
    throw new NullPointerException("ServiceProvider is null in OffHeapStore.Provider.");
  }
  TimeSource timeSource = getServiceProvider().getService(TimeSourceService.class).getTimeSource();

  SizedResourcePool offHeapPool = storeConfig.getResourcePools().getPoolForResource(getResourceType());
  if (!(offHeapPool.getUnit() instanceof MemoryUnit)) {
    throw new IllegalArgumentException("OffHeapStore only supports resources with memory unit");
  }
  MemoryUnit unit = (MemoryUnit)offHeapPool.getUnit();


  OffHeapStore<K, V> offHeapStore = new OffHeapStore<>(storeConfig, timeSource, eventDispatcher, unit.toBytes(offHeapPool
    .getSize()), getServiceProvider().getService(StatisticsService.class));
  createdStores.add(offHeapStore);
  return offHeapStore;
}
 
Example #8
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 #9
Source File: BasicClusteredCacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testClusteredCacheTwoClients() throws Exception {
  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
      newCacheManagerBuilder()
          .with(cluster(CLUSTER_URI).autoCreate(c -> c))
          .withCache("clustered-cache", newCacheConfigurationBuilder(Long.class, String.class,
              ResourcePoolsBuilder.newResourcePoolsBuilder().heap(100, EntryUnit.ENTRIES)
                  .with(clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)))
              .withService(new ClusteredStoreConfiguration(Consistency.STRONG)));

  try (PersistentCacheManager cacheManager1 = clusteredCacheManagerBuilder.build(true)) {
    try (PersistentCacheManager cacheManager2 = clusteredCacheManagerBuilder.build(true)) {

      final Cache<Long, String> cache1 = cacheManager1.getCache("clustered-cache", Long.class, String.class);
      final Cache<Long, String> cache2 = cacheManager2.getCache("clustered-cache", Long.class, String.class);

      assertThat(cache2.get(1L), nullValue());
      cache1.put(1L, "value1");
      assertThat(cache2.get(1L), is("value1"));
      assertThat(cache1.get(1L), is("value1"));
      cache1.put(1L, "value2");
      assertThat(cache2.get(1L), is("value2"));
      assertThat(cache1.get(1L), is("value2"));
    }
  }
}
 
Example #10
Source File: CacheManagerListenerInteractionsTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheManagerListener_called_after_configuration_updated() throws Exception {
  EhcacheManager cacheManager = (EhcacheManager) CacheManagerBuilder.newCacheManagerBuilder()
    .build();

  CacheManagerListener cacheManagerListener =  spy(new AssertiveCacheManagerListener(cacheManager.getRuntimeConfiguration()));
  cacheManager.registerListener(cacheManagerListener);
  cacheManager.init();

  CacheConfiguration<String, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
    newResourcePoolsBuilder()
      .heap(10, EntryUnit.ENTRIES)
      .offheap(1, MemoryUnit.MB))
    .build();

  cacheManager.createCache(CACHE_NAME, cacheConfiguration);
  verify(cacheManagerListener).cacheAdded(eq(CACHE_NAME), (Cache<?, ?>) isNotNull());
  cacheManager.removeCache(CACHE_NAME);
  verify(cacheManagerListener).cacheRemoved(eq(CACHE_NAME), (Cache<?, ?>) isNotNull());
}
 
Example #11
Source File: TestUserManagedCache.java    From jframe with Apache License 2.0 6 votes vote down vote up
public void persistenceServiceTest() {
    LocalPersistenceService persistenceService = new DefaultLocalPersistenceService(
            new DefaultPersistenceConfiguration(new File("", "myUserData")));

    PersistentUserManagedCache<Long, String> cache = UserManagedCacheBuilder
            .newUserManagedCacheBuilder(Long.class, String.class)
            .with(new UserManagedPersistenceContext<Long, String>("cache-name", persistenceService))
            .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10L, EntryUnit.ENTRIES).disk(10L,
                    MemoryUnit.MB, true))
            .build(true);

    // Work with the cache
    cache.put(42L, "The Answer!");
    // assertThat(cache.get(42L), is("The Answer!"));

    cache.close();
    try {
        cache.destroy();
    } catch (CachePersistenceException e) {
        e.printStackTrace();
    }

    persistenceService.stop();
}
 
Example #12
Source File: ClusteredResourcePoolUpdationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
  UnitTestConnectionService.add(CLUSTER_URI,
    new UnitTestConnectionService.PassthroughServerBuilder()
      .resource("primary-server-resource", 8, MemoryUnit.MB)
      .resource("secondary-server-resource", 8, MemoryUnit.MB)
      .build());

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER_URI).autoCreate(server -> server
      .defaultServerResource("primary-server-resource")
      .resourcePool("resource-pool-a", 2, MemoryUnit.MB, "secondary-server-resource")
      .resourcePool("resource-pool-b", 4, MemoryUnit.MB)))
    .withCache("dedicated-cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
        .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 4, MemoryUnit.MB))))
    .withCache("shared-cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
        .with(ClusteredResourcePoolBuilder.clusteredShared("resource-pool-a"))))
    .build();
  cacheManager.init();

  dedicatedCache = cacheManager.getCache("dedicated-cache", Long.class, String.class);
  sharedCache = cacheManager.getCache("shared-cache", Long.class, String.class);
}
 
Example #13
Source File: EventNotificationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testEventOrderForUpdateThatTriggersEviction () {
  CacheConfiguration<Long, SerializableObject> cacheConfiguration = newCacheConfigurationBuilder(Long.class, SerializableObject.class,
      newResourcePoolsBuilder()
          .heap(1L, EntryUnit.ENTRIES).offheap(1l, MemoryUnit.MB).build()).build();

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration)
      .build(true);
  Cache<Long, SerializableObject> cache = cacheManager.getCache("cache", Long.class, SerializableObject.class);
  cache.getRuntimeConfiguration().registerCacheEventListener(listener1, EventOrdering.ORDERED, EventFiring.SYNCHRONOUS, EnumSet
      .of(EventType.EVICTED, EventType.CREATED, EventType.UPDATED, EventType.REMOVED));
  SerializableObject object1 = new SerializableObject(0xAAE60);     // 700 KB
  SerializableObject object2 = new SerializableObject(0xDBBA0);     // 900 KB

  cache.put(1L, object1);
  cache.put(1L, object2);
  assertThat(listener1.eventTypeHashMap.get(EventType.EVICTED), lessThan(listener1.eventTypeHashMap.get(EventType.CREATED)));

  cacheManager.close();
}
 
Example #14
Source File: StatefulSerializerWithStateRepositoryTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testStatefulSerializerWithDiskStateRepositoryDifferentPersistenceServices() throws Exception {
  CacheManagerBuilder<PersistentCacheManager> cmBuilder = newCacheManagerBuilder().with(persistence(temporaryFolder.newFolder()
      .getAbsolutePath()))
      .withCache("myCache", newCacheConfigurationBuilder(Long.class, Person.class, heap(10).disk(50, MemoryUnit.MB, true))
          .withValueSerializer(CompactJavaSerializer.asTypedSerializer()));
  PersistentCacheManager cacheManager = cmBuilder.build(true);

  Cache<Long, Person> myCache = cacheManager.getCache("myCache", Long.class, Person.class);

  myCache.put(42L, new Person("John", 42));
  myCache.put(35L, new Person("Marie", 35));

  cacheManager.close();

  cacheManager = cmBuilder.build(true);

  myCache = cacheManager.getCache("myCache", Long.class, Person.class);

  assertThat(myCache.get(42L).getName(), is("John"));
}
 
Example #15
Source File: BasicClusteredCacheOpsReplicationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void startServers() throws Exception {
  CLUSTER.getClusterControl().startAllServers();
  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder
      = CacheManagerBuilder.newCacheManagerBuilder()
      .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER.getConnectionURI().resolve("/cm-replication"))
          .timeouts(TimeoutsBuilder.timeouts() // we need to give some time for the failover to occur
              .read(Duration.ofMinutes(1))
              .write(Duration.ofMinutes(1)))
          .autoCreate(server -> server.defaultServerResource("primary-server-resource")));
  cacheManager = clusteredCacheManagerBuilder.build(true);
  CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder().heap(100, EntryUnit.ENTRIES)
          .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 1, MemoryUnit.MB)))
      .withService(ClusteredStoreConfigurationBuilder.withConsistency(cacheConsistency))
      .build();

  cacheOne = cacheManager.createCache(testName.getMethodName() + "-1", config);
  cacheTwo = cacheManager.createCache(testName.getMethodName() + "-2", config);
}
 
Example #16
Source File: SerializerCountingTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testOffHeapOnHeapCopyPutGet() {
  Cache<Long, String> cache = cacheManager.createCache("offHeap", newCacheConfigurationBuilder(Long.class, String.class,
                                        newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).offheap(10, MemoryUnit.MB))
          .withService(new DefaultCopierConfiguration<>(SerializingCopier.<Long>asCopierClass(), DefaultCopierConfiguration.Type.KEY))
          .withService(new DefaultCopierConfiguration<>(SerializingCopier.<String>asCopierClass(), DefaultCopierConfiguration.Type.VALUE))
          .build()
  );

  cache.put(42L, "TheAnswer");
  assertCounters(2, 1, 0, 1, 0, 0);
  printSerializationCounters("Put OffheapOnHeapCopy");
  cache.get(42L);
  assertCounters(1, 1, 1, 0, 2, 0);
  printSerializationCounters("Get OffheapOnHeapCopy fault");
  cache.get(42L);
  assertCounters(0, 0, 0, 0, 1, 0);
  printSerializationCounters("Get OffheapOnHeapCopy faulted");

  cache.put(42L, "Wrong ...");
  assertCounters(3, 2, 2, 1, 0, 0);
  printSerializationCounters("Put OffheapOnHeapCopy (update faulted)");
}
 
Example #17
Source File: Tiering.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void byteSizedTieredCache() {
  // tag::byteSizedTieredCache[]
  CacheConfiguration<Long, String> usesConfiguredInCacheConfig = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
    ResourcePoolsBuilder.newResourcePoolsBuilder()
      .heap(10, MemoryUnit.KB) // <1>
      .offheap(10, MemoryUnit.MB)) // <2>
    .withSizeOfMaxObjectGraph(1000)
    .withSizeOfMaxObjectSize(1000, MemoryUnit.B) // <3>
    .build();

  CacheConfiguration<Long, String> usesDefaultSizeOfEngineConfig = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
    ResourcePoolsBuilder.newResourcePoolsBuilder()
      .heap(10, MemoryUnit.KB))
    .build();

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withDefaultSizeOfMaxObjectSize(500, MemoryUnit.B)
    .withDefaultSizeOfMaxObjectGraph(2000) // <4>
    .withCache("usesConfiguredInCache", usesConfiguredInCacheConfig)
    .withCache("usesDefaultSizeOfEngine", usesDefaultSizeOfEngineConfig)
    .build(true);
  // end::byteSizedTieredCache[]
}
 
Example #18
Source File: LeaseTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Parameterized.Parameters
public static ResourcePoolsBuilder[] data() {
  return new ResourcePoolsBuilder[]{
    ResourcePoolsBuilder.newResourcePoolsBuilder()
      .with(clusteredDedicated("primary-server-resource", 1, MemoryUnit.MB)),
    ResourcePoolsBuilder.newResourcePoolsBuilder()
      .heap(10, EntryUnit.ENTRIES)
      .with(clusteredDedicated("primary-server-resource", 1, MemoryUnit.MB))
  };
}
 
Example #19
Source File: SizeOfEngineLimits.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
public MemoryUnit getUnit() {
  MemoryType value = sizeoflimits.getMaxObjectSize();
  if (value == null) {
    return MemoryUnit.valueOf(new ObjectFactory().createMemoryType().getUnit().value().toUpperCase());
  } else {
    return MemoryUnit.valueOf(value.getUnit().value().toUpperCase());
  }
}
 
Example #20
Source File: XmlConfigurationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testResourcesCaches() throws Exception {
  final URL resource = XmlConfigurationTest.class.getResource("/configs/resources-caches.xml");
  XmlConfiguration xmlConfig = new XmlConfiguration(new XmlConfiguration(resource));

  CacheConfiguration<?, ?> tieredCacheConfig = xmlConfig.getCacheConfigurations().get("tiered");
  assertThat(tieredCacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getSize(), equalTo(10L));
  assertThat(tieredCacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.DISK).getSize(), equalTo(100L));
  assertThat(tieredCacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.DISK).isPersistent(), is(false));

  CacheConfiguration<?, ?> tieredPersistentCacheConfig = xmlConfig.getCacheConfigurations().get("tieredPersistent");
  assertThat(tieredPersistentCacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getSize(), equalTo(10L));
  assertThat(tieredPersistentCacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.DISK).getSize(), equalTo(100L));
  assertThat(tieredPersistentCacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.DISK).isPersistent(), is(true));

  CacheConfiguration<?, ?> tieredOffHeapCacheConfig = xmlConfig.getCacheConfigurations().get("tieredOffHeap");
  assertThat(tieredOffHeapCacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getSize(), equalTo(10L));
  assertThat(tieredOffHeapCacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.OFFHEAP).getSize(), equalTo(10L));
  assertThat(tieredOffHeapCacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.OFFHEAP).getUnit(), equalTo(MemoryUnit.MB));

  CacheConfiguration<?, ?> explicitHeapOnlyCacheConfig = xmlConfig.getCacheConfigurations().get("explicitHeapOnly");
  assertThat(explicitHeapOnlyCacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getSize(), equalTo(15L));
  assertThat(explicitHeapOnlyCacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.DISK), is(nullValue()));

  CacheConfiguration<?, ?> implicitHeapOnlyCacheConfig = xmlConfig.getCacheConfigurations().get("directHeapOnly");
  assertThat(implicitHeapOnlyCacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getSize(), equalTo(25L));
  assertThat(implicitHeapOnlyCacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.DISK), is(nullValue()));
}
 
Example #21
Source File: DefaultSizeOfEngineProviderConfigurationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidArguments() {
  DefaultSizeOfEngineProviderConfiguration configuration = new DefaultSizeOfEngineProviderConfiguration(10l, MemoryUnit.B, 10l);
  assertThat(configuration.getMaxObjectGraphSize(), equalTo(10l));
  assertThat(configuration.getMaxObjectSize(), equalTo(10l));
  assertThat(configuration.getUnit(), equalTo(MemoryUnit.B));
}
 
Example #22
Source File: DefaultSizeOfEngineProviderConfigurationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeriveDetachesCorrectly() {
  DefaultSizeOfEngineProviderConfiguration configuration = new DefaultSizeOfEngineProviderConfiguration(42L, MemoryUnit.B, 100L);

  DefaultSizeOfEngineProviderConfiguration derived = configuration.build(configuration.derive());

  assertThat(derived, is(not(sameInstance(configuration))));
  assertThat(derived.getMaxObjectGraphSize(), is(configuration.getMaxObjectGraphSize()));
  assertThat(derived.getMaxObjectSize(), is(configuration.getMaxObjectSize()));
  assertThat(derived.getUnit(), is(configuration.getUnit()));
}
 
Example #23
Source File: ClusteredStoreEventsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setup() throws Exception {
  UnitTestConnectionService.add(
      CLUSTER_URI,
      new UnitTestConnectionService.PassthroughServerBuilder().resource("defaultResource", 8, MemoryUnit.MB).build()
  );

  Connection connection = new UnitTestConnectionService().connect(CLUSTER_URI, new Properties());
  ClusterTierManagerClientEntityFactory entityFactory = new ClusterTierManagerClientEntityFactory(connection, Runnable::run);

  ServerSideConfiguration serverConfig =
      new ServerSideConfiguration("defaultResource", Collections.emptyMap());
  entityFactory.create("TestCacheManager", serverConfig);

  ClusteredResourcePool resourcePool = ClusteredResourcePoolBuilder.clusteredDedicated(4, MemoryUnit.MB);
  ServerStoreConfiguration serverStoreConfiguration = new ServerStoreConfiguration(resourcePool.getPoolAllocation(),
    Long.class.getName(), String.class.getName(), LongSerializer.class.getName(), StringSerializer.class.getName(), null, false);
  ClusterTierClientEntity clientEntity = entityFactory.fetchOrCreateClusteredStoreEntity("TestCacheManager", CACHE_IDENTIFIER, serverStoreConfiguration, ClusteringServiceConfiguration.ClientMode.AUTO_CREATE, false);
  clientEntity.validate(serverStoreConfiguration);
  ServerStoreProxy serverStoreProxy = new CommonServerStoreProxy(CACHE_IDENTIFIER, clientEntity, mock(ServerCallback.class));

  testTimeSource = new TestTimeSource();

  codec = new OperationsCodec<>(new LongSerializer(), new StringSerializer());
  ChainResolver<Long, String> resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1000)));

  StoreEventDispatcher<Long, String> storeEventDispatcher = mock(StoreEventDispatcher.class);
  storeEventSink = mock(StoreEventSink.class);
  when(storeEventDispatcher.eventSink()).thenReturn(storeEventSink);

  ClusteredStore<Long, String> store = new ClusteredStore<>(config, codec, resolver, serverStoreProxy, testTimeSource, storeEventDispatcher, new DefaultStatisticsService());
  serverCallback = new ClusteredStore.Provider().getServerCallback(store);
}
 
Example #24
Source File: TerminatedServerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Ignore("ClusteredStore.iterator() is not implemented")
@Test
public void testTerminationThenIterator() throws Exception {
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
      CacheManagerBuilder.newCacheManagerBuilder()
          .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER.get().getConnectionURI().resolve("/").resolve(testName.getMethodName()))
            .timeouts(TimeoutsBuilder.timeouts().read(Duration.of(1, ChronoUnit.SECONDS)).build())
              .autoCreate(server -> server.defaultServerResource("primary-server-resource")))
      .withCache("simple-cache",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
              ResourcePoolsBuilder.newResourcePoolsBuilder()
                  .with(ClusteredResourcePoolBuilder.clusteredDedicated(4, MemoryUnit.MB))));
  PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false);
  cacheManager.init();

  Cache<Long, String> cache = cacheManager.getCache("simple-cache", Long.class, String.class);
  cache.put(1L, "un");
  cache.put(2L, "deux");
  cache.put(3L, "trois");

  CLUSTER.get().getClusterControl().terminateAllServers();

  Iterator<Cache.Entry<Long, String>> value = new TimeLimitedTask<Iterator<Cache.Entry<Long,String>>>(ofSeconds(5)) {
    @Override
    Iterator<Cache.Entry<Long, String>> runTask() {
      return cache.iterator();
    }
  }.run();

  assertThat(value.hasNext()).isFalse();
}
 
Example #25
Source File: ClusteredStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  UnitTestConnectionService.add(
      CLUSTER_URI,
      new UnitTestConnectionService.PassthroughServerBuilder().resource("defaultResource", 8, MemoryUnit.MB).build()
  );

  Connection connection = new UnitTestConnectionService().connect(CLUSTER_URI, new Properties());
  ClusterTierManagerClientEntityFactory entityFactory = new ClusterTierManagerClientEntityFactory(connection, Runnable::run);

  ServerSideConfiguration serverConfig =
      new ServerSideConfiguration("defaultResource", Collections.emptyMap());
  entityFactory.create("TestCacheManager", serverConfig);

  ClusteredResourcePool resourcePool = ClusteredResourcePoolBuilder.clusteredDedicated(4, MemoryUnit.MB);
  ServerStoreConfiguration serverStoreConfiguration = new ServerStoreConfiguration(resourcePool.getPoolAllocation(),
    Long.class.getName(), String.class.getName(), LongSerializer.class.getName(), StringSerializer.class.getName(), null, false);
  ClusterTierClientEntity clientEntity = entityFactory.fetchOrCreateClusteredStoreEntity("TestCacheManager", CACHE_IDENTIFIER, serverStoreConfiguration, ClusteringServiceConfiguration.ClientMode.AUTO_CREATE, false);
  clientEntity.validate(serverStoreConfiguration);
  ServerStoreProxy serverStoreProxy = new CommonServerStoreProxy(CACHE_IDENTIFIER, clientEntity, mock(ServerCallback.class));

  TestTimeSource testTimeSource = new TestTimeSource();

  OperationsCodec<Long, String> codec = new OperationsCodec<>(new LongSerializer(), new StringSerializer());
  EternalChainResolver<Long, String> resolver = new EternalChainResolver<>(codec);
  store = new ClusteredStore<>(config, codec, resolver, serverStoreProxy, testTimeSource, new DefaultStoreEventDispatcher<>(8), new DefaultStatisticsService());
}
 
Example #26
Source File: SerializersTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private void testSerializerWithDiskCache(Serializer<Long> serializer) throws Exception {
  CacheManagerBuilder<PersistentCacheManager> cmBuilder =
    newCacheManagerBuilder()
      .with(persistence(temporaryFolder.newFolder().getAbsolutePath()))
      .withCache("diskCache",
        newCacheConfigurationBuilder(Long.class, Person.class, newResourcePoolsBuilder().disk(8, MemoryUnit.MB, true))
          .withKeySerializer(serializer)
      );
  cmBuilder.build(true);
}
 
Example #27
Source File: SerializersTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private void testSerializerWithHeapOffheapCache(Serializer<Long> serializer) throws Exception {
  CacheManagerBuilder<CacheManager> cmBuilder =
    newCacheManagerBuilder()
      .withCache("heapOffheapCache",
        newCacheConfigurationBuilder(Long.class, Person.class, newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).offheap(2, MemoryUnit.MB))
          .withKeySerializer(serializer)
      );
  cmBuilder.build(true);
}
 
Example #28
Source File: ReconnectDuringDestroyTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void reconnectAfterDestroyOneOfTheCache() throws Exception {
  try {
    CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
        .with(ClusteredResourcePoolBuilder.
          clusteredDedicated("primary-server-resource", 1, MemoryUnit.MB)))
      .withResilienceStrategy(new ThrowingResiliencyStrategy<>())
      .build();
    Cache<Long, String> cache1 = cacheManager.createCache("clustered-cache-1", config);
    Cache<Long, String> cache2 = cacheManager.createCache("clustered-cache-2", config);
    cache1.put(1L, "The one");
    cache1.put(2L, "The two");
    cache2.put(1L, "The one");
    cache2.put(2L, "The two");
    cacheManager.destroyCache("clustered-cache-1");

    // For reconnection.
    long delay = CLUSTER.input().plusSeconds(1L).toMillis();
    setDelay(delay, proxies);
    try {
      Thread.sleep(delay);
    } finally {
      setDelay(0L, proxies);
    }

    Cache<Long, String> cache2Again = cacheManager.getCache("clustered-cache-2", Long.class, String.class);
    assertThat(() -> cache2Again.get(1L), within(ofSeconds(10)).is("The one"));
    assertThat(cache2Again.get(2L), equalTo("The two"));
    cache2Again.put(3L, "The three");
    assertThat(cache2Again.get(3L), equalTo("The three"));
  } finally {
    cacheManager.close();
  }
}
 
Example #29
Source File: TestEhcache.java    From jframe with Apache License 2.0 5 votes vote down vote up
@Test
public void cacheConfigTest() {
    CacheConfiguration<Long, String> usesConfiguredInCacheConfig = CacheConfigurationBuilder
            .newCacheConfigurationBuilder(Long.class, String.class,
                    ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, MemoryUnit.KB).offheap(10,
                            MemoryUnit.MB))
            .withSizeOfMaxObjectGraph(1000).withSizeOfMaxObjectSize(1000, MemoryUnit.B).build();

    CacheConfiguration<Long, String> usesDefaultSizeOfEngineConfig = CacheConfigurationBuilder
            .newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder()
                    .heap(10, MemoryUnit.KB).offheap(10, MemoryUnit.MB))
            .build();

    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
            .withDefaultSizeOfMaxObjectSize(500, MemoryUnit.B).withDefaultSizeOfMaxObjectGraph(2000)
            .withCache("usesConfiguredInCache", usesConfiguredInCacheConfig)
            .withCache("usesDefaultSizeOfEngine", usesDefaultSizeOfEngineConfig).build(true);

    Cache<Long, String> usesConfiguredInCache = cacheManager.getCache("usesConfiguredInCache", Long.class,
            String.class);
    usesConfiguredInCache.put(1L, "one");
    
    // assertThat(usesConfiguredInCache.get(1L), equalTo("one"));

    Cache<Long, String> usesDefaultSizeOfEngine = cacheManager.getCache("usesDefaultSizeOfEngine", Long.class,
            String.class);
    usesDefaultSizeOfEngine.put(1L, "one");
    // assertThat(usesDefaultSizeOfEngine.get(1L), equalTo("one"));

    cacheManager.close();
}
 
Example #30
Source File: ResourcePoolsBuilderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithReplacingNoInitial() throws Exception {
  long newSize = 16;
  ResourceUnit mb = MemoryUnit.MB;
  SizedResourcePool newPool = new SizedResourcePoolImpl<>(HEAP, newSize, mb, false);

  ResourcePoolsBuilder builder = newResourcePoolsBuilder();
  ResourcePools resourcePools = builder.withReplacing(newPool).build();
  SizedResourcePool pool = resourcePools.getPoolForResource(HEAP);

  assertThat(pool.getSize(), is(newSize));
  assertThat(pool.getUnit(), is(mb));
}