org.ehcache.config.units.EntryUnit Java Examples

The following examples show how to use org.ehcache.config.units.EntryUnit. 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: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void threeTiersCacheManager() throws Exception {
  // tag::threeTiersCacheManager[]
  PersistentCacheManager persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .with(CacheManagerBuilder.persistence(new File(getStoragePath(), "myData"))) // <1>
      .withCache("threeTieredCache",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
              ResourcePoolsBuilder.newResourcePoolsBuilder()
                  .heap(10, EntryUnit.ENTRIES) // <2>
                  .offheap(1, MemoryUnit.MB) // <3>
                  .disk(20, MemoryUnit.MB, true) // <4>
              )
      ).build(true);

  Cache<Long, String> threeTieredCache = persistentCacheManager.getCache("threeTieredCache", Long.class, String.class);
  threeTieredCache.put(1L, "stillAvailableAfterRestart"); // <5>

  persistentCacheManager.close();
  // end::threeTiersCacheManager[]
}
 
Example #2
Source File: DefaultTierStatisticsTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
  CacheConfiguration<Long, String> cacheConfiguration =
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES))
      .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION)))
      .withService(new StoreStatisticsConfiguration(true)) // explicitly enable statistics
      .build();

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

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

  onHeap = new DefaultTierStatistics(cache, "OnHeap");
}
 
Example #3
Source File: DefaultTierStatisticsDisabledTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
  CacheConfiguration<Long, String> cacheConfiguration =
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES))
      .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION)))
      .build();

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

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

  onHeap = new DefaultTierStatistics(cache, "OnHeap");
}
 
Example #4
Source File: CacheManagerDestroyRemovesPersistenceTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateCacheWithSameAliasAfterDestroy() throws Exception {
  File file = new File(getStoragePath(), "testDestroy");
  initCacheManager(file);

  persistentCacheManager.destroyCache(PERSISTENT_CACHE);

  persistentCacheManager.createCache(PERSISTENT_CACHE, CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      newResourcePoolsBuilder()
          .heap(10, EntryUnit.ENTRIES)
          .disk(10L, MemoryUnit.MB, true))
      .build());

  assertNotNull(persistentCacheManager.getCache(PERSISTENT_CACHE, Long.class, String.class));

  persistentCacheManager.close();
}
 
Example #5
Source File: TieringTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
  public void testPersistentDiskCache() throws Exception {
    CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
        ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).disk(10L, MemoryUnit.MB, true))
        .build();

    PersistentCacheManager persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .with(new CacheManagerPersistenceConfiguration(new File(getClass().getClassLoader().getResource(".").toURI().getPath() + "/../../persistent-cache-data")))
        .withCache("persistent-cache", cacheConfiguration)
        .build(true);

    Cache<Long, String> cache = persistentCacheManager.getCache("persistent-cache", Long.class, String.class);

    // Comment the following line on subsequent run and see the test pass
    cache.put(42L, "That's the answer!");
    assertThat(cache.get(42L), is("That's the answer!"));

    // Uncomment the following line to nuke the disk store
//    persistentCacheManager.destroyCache("persistent-cache");

    persistentCacheManager.close();
  }
 
Example #6
Source File: Tiering.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void threeTiersCacheManager() throws Exception {
  // tag::threeTiersCacheManager[]
  PersistentCacheManager persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .with(cluster(CLUSTER_URI).autoCreate(c -> c)) // <1>
    .withCache("threeTierCache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
        ResourcePoolsBuilder.newResourcePoolsBuilder()
          .heap(10, EntryUnit.ENTRIES) // <2>
          .offheap(1, MemoryUnit.MB) // <3>
          .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)) // <4>
      )
    ).build(true);
  // end::threeTiersCacheManager[]

  persistentCacheManager.close();
}
 
Example #7
Source File: OffHeapOsgiTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
public static void testOffHeapClientClass() {
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withClassLoader(TestMethods.class.getClassLoader())
    .withCache("myCache", newCacheConfigurationBuilder(Long.class, Order.class, newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).offheap(2, MemoryUnit.MB))
      .build())
    .build(true);

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

  Order order = new Order(42L);
  cache.put(42L, order);

  assertTrue(cache.get(42L) instanceof Order);

  cache.replace(42L, order, new Order(-1L));

  assertEquals(-1L, cache.get(42L).id);
}
 
Example #8
Source File: WriteBehindTestBase.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
PersistentCacheManager createCacheManager(URI clusterUri) {
  CacheConfiguration<Long, String> cacheConfiguration =
    newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder()
                                                                               .heap(10, EntryUnit.ENTRIES)
                                                                               .offheap(1, MemoryUnit.MB)
                                                                               .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)))
      .withLoaderWriter(loaderWriter)
      .withService(WriteBehindConfigurationBuilder.newUnBatchedWriteBehindConfiguration())
      .withResilienceStrategy(new ThrowingResilienceStrategy<>())
      .withService(new ClusteredStoreConfiguration(Consistency.STRONG))
      .build();

  return CacheManagerBuilder
    .newCacheManagerBuilder()
    .with(cluster(clusterUri.resolve("/cm-wb")).timeouts(TimeoutsBuilder.timeouts().read(Duration.ofMinutes(1)).write(Duration.ofMinutes(1))).autoCreate(c -> c))
    .withCache(testName.getMethodName(), cacheConfiguration)
    .build(true);
}
 
Example #9
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 #10
Source File: TieringTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTieredOffHeapStore() throws Exception {
  CacheConfiguration<Long, String> tieredCacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).offheap(10, MemoryUnit.MB))
      .build();

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("tieredCache", tieredCacheConfiguration).build(true);

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

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

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

  cacheManager.close();
}
 
Example #11
Source File: BasicClusteredWriteBehindPassthroughTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
private PersistentCacheManager createCacheManager() {
  CacheConfiguration<Long, String> cacheConfiguration =
    newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder()
                                                                               .heap(10, EntryUnit.ENTRIES)
                                                                               .offheap(1, MemoryUnit.MB)
                                                                               .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)))
      .withLoaderWriter(loaderWriter)
      .withService(WriteBehindConfigurationBuilder.newUnBatchedWriteBehindConfiguration())
      .withService(new ClusteredStoreConfiguration(Consistency.STRONG))
      .build();

  return CacheManagerBuilder
    .newCacheManagerBuilder()
    .with(cluster(CLUSTER_URI).autoCreate(c -> c))
    .withCache(CACHE_NAME, cacheConfiguration)
    .build(true);
}
 
Example #12
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 #13
Source File: CacheConfigurationCustomizerEnabledAppendTest.java    From camel-spring-boot with Apache License 2.0 6 votes vote down vote up
@Order(Ordered.HIGHEST_PRECEDENCE)
@Bean
public ComponentCustomizer<EhcacheComponent> customizer() {
    return new ComponentCustomizer<EhcacheComponent>() {
        @Override
        public void customize(EhcacheComponent component) {
            component.addCachesConfigurations(Collections.singletonMap(
                CACHE_CONFIG_ID,
                CacheConfigurationBuilder.newCacheConfigurationBuilder(
                    String.class,
                    String.class,
                    ResourcePoolsBuilder.newResourcePoolsBuilder()
                        .heap(2100, EntryUnit.ENTRIES)
                        .offheap(2, MemoryUnit.MB))
                    .build()
            ));
        }
    };
}
 
Example #14
Source File: CacheConfigurationCustomizerEnabledReplaceTest.java    From camel-spring-boot with Apache License 2.0 6 votes vote down vote up
@Order(Ordered.HIGHEST_PRECEDENCE)
@Bean
public ComponentCustomizer<EhcacheComponent> customizer() {
    return new ComponentCustomizer<EhcacheComponent>() {
        @Override
        public void customize(EhcacheComponent component) {
            component.addCachesConfigurations(Collections.singletonMap(
                CACHE_CONFIG_ID,
                CacheConfigurationBuilder.newCacheConfigurationBuilder(
                    String.class,
                    String.class,
                    ResourcePoolsBuilder.newResourcePoolsBuilder()
                        .heap(2100, EntryUnit.ENTRIES)
                        .offheap(2, MemoryUnit.MB))
                    .build()
            ));
        }
    };
}
 
Example #15
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 #16
Source File: UserManagedCaches.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void userManagedListenerCache() throws Exception {
  // tag::userManagedListenerCache[]

  UserManagedCache<Long, String> cache = UserManagedCacheBuilder.newUserManagedCacheBuilder(Long.class, String.class)
      .withEventExecutors(Executors.newSingleThreadExecutor(), Executors.newFixedThreadPool(5)) // <1>
      .withEventListeners(CacheEventListenerConfigurationBuilder
          .newEventListenerConfiguration(ListenerObject.class, EventType.CREATED, EventType.UPDATED)
          .asynchronous()
          .unordered()) // <2>
      .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder()
          .heap(3, EntryUnit.ENTRIES))
      .build(true);

  cache.put(1L, "Put it");
  cache.put(1L, "Update it");

  cache.close();
  // end::userManagedListenerCache[]
}
 
Example #17
Source File: ClusteringManagementServiceTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void test_E_notifs_on_add_cache() throws Exception {
  cacheManager.createCache("cache-2", newCacheConfigurationBuilder(
    String.class, String.class,
    newResourcePoolsBuilder()
      .heap(10, EntryUnit.ENTRIES)
      .offheap(1, MemoryUnit.MB)
      .with(clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)))
    .build());

  Cluster cluster = readTopology();
  ContextContainer contextContainer = cluster.getClient(ehcacheClientIdentifier).get().getManagementRegistry().get().getContextContainer();
  assertThat(contextContainer.getSubContexts()).hasSize(4);

  TreeSet<String> cNames = contextContainer.getSubContexts().stream().map(ContextContainer::getValue).collect(Collectors.toCollection(TreeSet::new));
  assertThat(cNames).isEqualTo(new TreeSet<>(Arrays.asList("cache-2", "dedicated-cache-1", "shared-cache-2", "shared-cache-3")));

  if (cluster.serverStream().count() == 2) {
    waitForAllNotifications(
      "SERVER_ENTITY_CREATED", "ENTITY_REGISTRY_AVAILABLE", "EHCACHE_SERVER_STORE_CREATED", "SERVER_ENTITY_FETCHED", "CACHE_ADDED",
      "SERVER_ENTITY_CREATED", "ENTITY_REGISTRY_AVAILABLE", "EHCACHE_SERVER_STORE_CREATED"); // passive server
  } else {
    waitForAllNotifications(
      "SERVER_ENTITY_CREATED", "ENTITY_REGISTRY_AVAILABLE", "EHCACHE_SERVER_STORE_CREATED", "SERVER_ENTITY_FETCHED", "CACHE_ADDED");
  }
}
 
Example #18
Source File: NonClusteredCacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonClustered() throws Exception {

  /*
   * Ensure the cluster provider classes are loadable through the ServiceLoader mechanism.
   */
  assertThat(stream(spliterator(ClassLoading.servicesOfType(ServiceFactory.class).iterator(), Long.MAX_VALUE, 0), false).map(f -> f.getServiceType()).collect(Collectors.toList()),
    hasItems(ClusteredStore.Provider.class, ClusteringService.class));

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


  try (CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true)) {
    cacheManager.createCache("cache-1", cacheConfiguration);
    cacheManager.createCache("cache-2", cacheConfiguration);
  }
}
 
Example #19
Source File: UserManagedCaches.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void userManagedDiskCache() throws Exception {
  // tag::persistentUserManagedCache[]
  LocalPersistenceService persistenceService = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(new File(getStoragePath(), "myUserData"))); // <1>

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

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

  cache.close(); // <4>
  cache.destroy(); // <5>

  persistenceService.stop(); // <6>
  // end::persistentUserManagedCache[]
}
 
Example #20
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 #21
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 #22
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 #23
Source File: Tiering.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void threeTiersCacheManager() throws Exception {
  // tag::threeTiersCacheManager[]
  PersistentCacheManager persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .with(CacheManagerBuilder.persistence(new File(getStoragePath(), "myData")))
    .withCache("threeTieredCache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
        ResourcePoolsBuilder.newResourcePoolsBuilder()
          .heap(10, EntryUnit.ENTRIES)
          .offheap(1, MemoryUnit.MB)
          .disk(20, MemoryUnit.MB, true)
      )
    ).build(true);
  // end::threeTiersCacheManager[]

  persistentCacheManager.close();
}
 
Example #24
Source File: SerializerCountingTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testDiskOffHeapOnHeapCopyPutGet() {
  Cache<Long, String> cache = cacheManager.createCache("offHeap", newCacheConfigurationBuilder(Long.class, String.class,
                newResourcePoolsBuilder().heap(2, EntryUnit.ENTRIES).offheap(10, MemoryUnit.MB).disk(100, 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(3, 2, 0, 1, 0, 0);
  printSerializationCounters("Put DiskOffHeapOnHeapCopy");
  cache.get(42L);
  assertCounters(1, 1, 1, 0, 2, 0);
  printSerializationCounters("Get DiskOffHeapOnHeapCopy fault");
  cache.get(42L);
  assertCounters(0, 0, 0, 0, 1, 0);
  printSerializationCounters("Get DiskOffHeapOnHeapCopy faulted");

  cache.put(42L, "Wrong ...");
  assertCounters(3, 2, 2, 1, 0, 0);
  printSerializationCounters("Put DiskOffHeapOnHeapCopy (update faulted)");
}
 
Example #25
Source File: SerializerCountingTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testOffHeapPutGet() {
  Cache<Long, String> cache = cacheManager.createCache("offHeap", newCacheConfigurationBuilder(Long.class, String.class,
                                        newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).offheap(10, MemoryUnit.MB))
          .build()
  );

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

  cache.put(42L, "Wrong ...");
  assertCounters(1, 0, 2, 1, 0, 0);
  printSerializationCounters("Put OffHeap (update faulted)");
}
 
Example #26
Source File: XAStoreTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  transactionManagerWrapper = new TransactionManagerWrapper(testTransactionManager, new NullXAResourceRegistry());
  classLoader = ClassLoader.getSystemClassLoader();
  keySerializer = new JavaSerializer<>(classLoader);
  valueSerializer = new JavaSerializer<>(classLoader);
  CopyProvider copyProvider = new DefaultCopyProvider(new DefaultCopyProviderConfiguration());
  keyCopier = copyProvider.createKeyCopier(Long.class, keySerializer);
  valueCopier = copyProvider.createValueCopier(valueClass, valueSerializer);
  Store.Configuration<Long, SoftLock<String>> onHeapConfig = new StoreConfigurationImpl<>(Long.class, valueClass,
    null, classLoader, ExpiryPolicyBuilder.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder()
    .heap(10, EntryUnit.ENTRIES)
    .build(),
    0, keySerializer, valueSerializer);
  testTimeSource = new TestTimeSource();
  eventDispatcher = NullStoreEventDispatcher.nullStoreEventDispatcher();
  onHeapStore = new OnHeapStore<>(onHeapConfig, testTimeSource, keyCopier, valueCopier, new NoopSizeOfEngine(), eventDispatcher, new DefaultStatisticsService());
  journal = new TransientJournal<>();
}
 
Example #27
Source File: NonXACacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonXA() throws Exception {

  /*
   * Ensure the XA provider classes are loadable through the ServiceLoader mechanism.
   */
  assertThat(stream(spliterator(ClassLoading.servicesOfType(ServiceFactory.class).iterator(), Long.MAX_VALUE, 0), false).map(s -> s.getServiceType()).collect(toList()),
    hasItems(XAStore.Provider.class, TransactionManagerProvider.class));

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


  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true);

  cacheManager.createCache("cache-1", cacheConfiguration);
  cacheManager.createCache("cache-2", cacheConfiguration);

  cacheManager.close();
}
 
Example #28
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 #29
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 #30
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"));
    }
  }
}