org.ehcache.CacheManager Java Examples

The following examples show how to use org.ehcache.CacheManager. 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: AbstractWriteBehindTestBase.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFilledBatchedIsWritten() throws Exception {
  WriteBehindTestLoaderWriter<String, String> loaderWriter = new WriteBehindTestLoaderWriter<>();
  CacheLoaderWriterProvider cacheLoaderWriterProvider = getMockedCacheLoaderWriterProvider(loaderWriter);

  try (CacheManager cacheManager = managerBuilder().using(cacheLoaderWriterProvider).build(true)) {
    Cache<String, String> testCache = cacheManager.createCache("testFilledBatchedIsWritten", configurationBuilder()
      .withLoaderWriter(loaderWriter)
      .withService(newBatchedWriteBehindConfiguration(Long.MAX_VALUE, SECONDS, 2).build())
      .build());

    CountDownLatch latch = new CountDownLatch(2);
    loaderWriter.setLatch(latch);

    testCache.put("key1", "value");
    testCache.put("key2", "value");

    if (latch.await(10, SECONDS)) {
      assertThat(loaderWriter.getValueList("key1"), contains("value"));
      assertThat(loaderWriter.getValueList("key2"), contains("value"));
    } else {
      fail("Took too long to write, assuming batch is not going to be written");
    }
  }
}
 
Example #2
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 #3
Source File: IntegrationConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testThreadPoolsUsingDefaultPool() throws Exception {
  Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/thread-pools.xml"));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
  cacheManager.init();
  try {
    Cache<String, String> cache = cacheManager.createCache("testThreadPools", newCacheConfigurationBuilder(String.class, String.class, heap(10))
            .withService(new DefaultCacheLoaderWriterConfiguration(ThreadRememberingLoaderWriter.class))
            .withService(newUnBatchedWriteBehindConfiguration())
            .build());

    cache.put("foo", "bar");

    ThreadRememberingLoaderWriter.USED.acquireUninterruptibly();

    assertThat(ThreadRememberingLoaderWriter.LAST_SEEN_THREAD.getName(), containsString("[big]"));
  } finally {
    cacheManager.close();
  }
}
 
Example #4
Source File: AbstractWriteBehindTestBase.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBatchedOverwrittenKeyReturnsNewValue() throws Exception {
  @SuppressWarnings("unchecked")
  CacheLoaderWriter<String, String> loaderWriter = mock(CacheLoaderWriter.class);
  when(loaderWriter.load("key")).thenReturn("value");
  CacheLoaderWriterProvider cacheLoaderWriterProvider = getMockedCacheLoaderWriterProvider(loaderWriter);

  try (CacheManager cacheManager = managerBuilder().using(cacheLoaderWriterProvider).build(true)) {
    Cache<String, String> testCache = cacheManager.createCache("testBatchedOverwrittenKeyReturnsNewValue", configurationBuilder()
      .withLoaderWriter(loaderWriter)
      .withService(newBatchedWriteBehindConfiguration(Long.MAX_VALUE, SECONDS, 2).build())
      .build());

    assertThat(testCache.get("key"), is("value"));

    testCache.put("key", "value2");

    assertThat(testCache.get("key"), is("value2"));
  }
}
 
Example #5
Source File: StatefulSerializerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testXAWithStatefulSerializer() throws Exception {
  BitronixTransactionManager manager = TransactionManagerServices.getTransactionManager();
  try (CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .using(new LookupTransactionManagerProviderConfiguration(
          BitronixTransactionManagerLookup.class))
        .withCache("xaCache",
          CacheConfigurationBuilder
            .newCacheConfigurationBuilder(Long.class, Person.class,
              ResourcePoolsBuilder.heap(5))
            .withExpiry(ExpiryPolicyBuilder.noExpiration()).withService(new XAStoreConfiguration("xaCache"))
            .build())
        .build(true)) {

    Cache<Long, Person> cache = cacheManager.getCache("xaCache", Long.class, Person.class);
    manager.begin();
    cache.put(1L, new Person("James", 42));
    manager.commit();

    manager.begin();
    assertNotNull(cache.get(1L));
    manager.commit();
  } finally {
    manager.shutdown();
  }
}
 
Example #6
Source File: ClusteredXML.java    From ehcache3-samples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  LOGGER.info("Creating clustered cache manager from XML");

  URL myUrl = ClusteredXML.class.getResource("/ehcache.xml");
  Configuration xmlConfig = new XmlConfiguration(myUrl);
  try (CacheManager cacheManager = newCacheManager(xmlConfig)) {
    cacheManager.init();
    
    Cache<Long, String> basicCache = cacheManager.getCache("basicCache", Long.class, String.class);
    
    LOGGER.info("Getting from cache");
    String value = basicCache.get(1L);
    LOGGER.info("Retrieved '{}'", value);

    LOGGER.info("Closing cache manager");
  }

  LOGGER.info("Exiting");
}
 
Example #7
Source File: AbstractWriteBehindTestBase.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testWrites() throws Exception {
  WriteBehindTestLoaderWriter<String, String> loaderWriter = new WriteBehindTestLoaderWriter<>();
  CacheLoaderWriterProvider cacheLoaderWriterProvider = getMockedCacheLoaderWriterProvider(loaderWriter);

  try (CacheManager cacheManager = managerBuilder().using(cacheLoaderWriterProvider).build(true)) {
    Cache<String, String> testCache = cacheManager.createCache("testWrites", CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class, heap(10))
      .withLoaderWriter(loaderWriter)
      .withService(newUnBatchedWriteBehindConfiguration().concurrencyLevel(3).queueSize(10).build())
      .build());

    CountDownLatch countDownLatch = new CountDownLatch(4);
    loaderWriter.setLatch(countDownLatch);
    testCache.put("test1", "test1");
    testCache.put("test2", "test2");
    testCache.put("test3", "test3");
    testCache.remove("test2");

    countDownLatch.await(2, SECONDS);

    assertThat(loaderWriter.getData().get("test1"), contains("test1"));
    assertThat(loaderWriter.getData().get("test2"), contains("test2", null));
    assertThat(loaderWriter.getData().get("test3"), contains("test3"));
  }
}
 
Example #8
Source File: BasicXML.java    From ehcache3-samples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  LOGGER.info("Creating cache manager via XML resource");
  Configuration xmlConfig = new XmlConfiguration(BasicXML.class.getResource("/ehcache.xml"));
  try (CacheManager cacheManager = newCacheManager(xmlConfig)) {
    cacheManager.init();

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

    LOGGER.info("Putting to cache");
    basicCache.put(1L, "da one!");
    String value = basicCache.get(1L);
    LOGGER.info("Retrieved '{}'", value);

    LOGGER.info("Closing cache manager");
  }

  LOGGER.info("Exiting");
}
 
Example #9
Source File: IntegrationConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheEventListener() throws Exception {
  Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/ehcache-cacheEventListener.xml"));
  assertThat(configuration.getCacheConfigurations().containsKey("bar"), is(true));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
  cacheManager.init();
  final Cache<Number, String> cache = cacheManager.getCache("bar", Number.class, String.class);
  cache.put(10, "dog");
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.CREATED));
  cache.put(10, "cat");
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.UPDATED));
  cache.remove(10);
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.REMOVED));
  cache.put(10, "dog");
  resetValues();
  assertThat(configuration.getCacheConfigurations().containsKey("template1"), is(true));
  final Cache<Number, String> templateCache = cacheManager.getCache("template1", Number.class, String.class);
  templateCache.put(10,"cat");
  assertThat(TestCacheEventListener.FIRED_EVENT, nullValue());
  templateCache.put(10, "dog");
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.UPDATED));
}
 
Example #10
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void cachemanagerExample() {
  // tag::cachemanagerExample[]
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() // <1>
      .withCache("preConfigured",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))) // <2>
      .build(); // <3>
  cacheManager.init(); // <4>

  Cache<Long, String> preConfigured =
      cacheManager.getCache("preConfigured", Long.class, String.class); // <5>

  Cache<Long, String> myCache = cacheManager.createCache("myCache", // <6>
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)));

  myCache.put(1L, "da one!"); // <7>
  String value = myCache.get(1L); // <8>

  cacheManager.removeCache("preConfigured"); // <9>

  cacheManager.close(); // <10>
  // end::cachemanagerExample[]
}
 
Example #11
Source File: ClusteredLoaderWriterTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicOps() {
  client1 = cacheManager.createCache("basicops" + cacheConsistency.name(), configuration);
  assertThat(sor.isEmpty(), is(true));

  Set<Long> keys = new HashSet<>();
  ThreadLocalRandom.current().longs(10).forEach(x -> {
    keys.add(x);
    client1.put(x, Long.toString(x));
  });

  assertThat(sor.size(), is(10));

  CacheManager anotherCacheManager = newCacheManager();
  Cache<Long, String> client2 = anotherCacheManager.createCache("basicops" + cacheConsistency.name(),
          getCacheConfig());
  Map<Long, String> all = client2.getAll(keys);
  assertThat(all.keySet(), containsInAnyOrder(keys.toArray()));

  keys.stream().limit(3).forEach(client2::remove);

  assertThat(sor.size(), is(7));
}
 
Example #12
Source File: ArbitraryCacheManagerTest.java    From ehcache-shiro with Apache License 2.0 6 votes vote down vote up
/**
 * Test showing issues:
 * <p>
 * https://github.com/ehcache/ehcache-shiro/issues/12
 * https://github.com/ehcache/ehcache-shiro/issues/13
 *
 * @throws Exception
 */
@Test
public void testArbitraryCacheManager() throws Exception {
  ehcacheShiroManager.init();
  CacheManager firstCacheManager = ehcacheShiroManager.getCacheManager();
  Assert.assertNotNull(firstCacheManager);

  ehcacheShiroManager.setCacheManager(cacheManager);
  CacheManager secondCacheManager = ehcacheShiroManager.getCacheManager();
  Assert.assertNotSame(firstCacheManager, secondCacheManager);
  Assert.assertNotEquals(firstCacheManager, secondCacheManager);

  ehcacheShiroManager.destroy();

  Assert.assertEquals(Status.UNINITIALIZED, firstCacheManager.getStatus());
  Assert.assertEquals(Status.AVAILABLE, secondCacheManager.getStatus());
}
 
Example #13
Source File: ArbitraryCacheManagerTest.java    From ehcache-shiro with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoubleInit() throws Exception {
  ehcacheShiroManager.init();
  CacheManager firstCacheManager = ehcacheShiroManager.getCacheManager();
  Assert.assertNotNull(firstCacheManager);

  ehcacheShiroManager.setCacheManagerConfigFile("notValidPath");
  ehcacheShiroManager.init();
  CacheManager secondCacheManager = ehcacheShiroManager.getCacheManager();
  Assert.assertNotNull(secondCacheManager);

  Assert.assertEquals(firstCacheManager, secondCacheManager);
  Assert.assertSame(firstCacheManager, secondCacheManager);

  ehcacheShiroManager.destroy();
}
 
Example #14
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPutAll_without_cache_writer() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

  CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

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

  HashMap<String, String> stringStringHashMap = new HashMap<>();
  for (int i = 0; i < 3; i++) {
    stringStringHashMap.put("key" + i, "value" + i);
  }

  // the call to putAll
  myCache.putAll(stringStringHashMap);

  for (int i = 0; i < 3; i++) {
    assertThat(myCache.get("key" + i), is("value" + i));
  }

}
 
Example #15
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 #16
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheEvictionAdvisor() throws Exception {
  // tag::cacheEvictionAdvisor[]
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
                                                                                      ResourcePoolsBuilder.heap(2L)) // <1>
      .withEvictionAdvisor(new OddKeysEvictionAdvisor<>()) // <2>
      .build();

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

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

  // Work with the cache
  cache.put(42L, "The Answer!");
  cache.put(41L, "The wrong Answer!");
  cache.put(39L, "The other wrong Answer!");

  cacheManager.close();
  // end::cacheEvictionAdvisor[]
}
 
Example #17
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 #18
Source File: ClusteredIterationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testIterationTerminatedWithException() {
  try (CacheManager cacheManager = createTestCacheManager()) {
    Cache<Long, byte[]> cache = cacheManager.getCache(testName.getMethodName(), Long.class, byte[].class);

    byte[] data = new byte[101 * 1024];
    cache.put(1L, data);
    cache.put(2L, data);

    Iterator<Cache.Entry<Long, byte[]>> iterator = cache.iterator();

    assertThat(iterator.next(), notNullValue());
    assertThat(iterator.next(), notNullValue());

    try {
      iterator.next();
      fail("Expected NoSuchElementException");
    } catch (NoSuchElementException e) {
      //expected
    }
  }
}
 
Example #19
Source File: ThreadPoolsTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoDefaultThreadPoolFails() throws Exception {
  PooledExecutionServiceConfiguration executionServiceConfiguration = new PooledExecutionServiceConfiguration();
  executionServiceConfiguration.addPool("foo", 2, 4);
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .using(executionServiceConfiguration)
      .build(true);

  try {
    cacheManager.createCache("testCache",
        CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
            .build());
    fail("expected IllegalStateException");
  } catch (IllegalStateException ise) {
    // expected
  }

  cacheManager.close();
}
 
Example #20
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheEventListener() {
  // tag::cacheEventListener[]
  CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
      .newEventListenerConfiguration(new ListenerObject(), EventType.CREATED, EventType.UPDATED) // <1>
      .unordered().asynchronous(); // <2>

  final CacheManager manager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("foo",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class, ResourcePoolsBuilder.heap(10))
              .withService(cacheEventListenerConfiguration) // <3>
      ).build(true);

  final Cache<String, String> cache = manager.getCache("foo", String.class, String.class);
  cache.put("Hello", "World"); // <4>
  cache.put("Hello", "Everyone"); // <5>
  cache.remove("Hello"); // <6>
  // end::cacheEventListener[]

  manager.close();
}
 
Example #21
Source File: TestEviction.java    From jframe with Apache License 2.0 6 votes vote down vote up
public void evictionTest() {
    CacheConfiguration<Long, String> cacheConfiguration =
            CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(2L)).build();
    // .withEvictionAdvisor(new OddKeysEvictionAdvisor<Long, String>()).build();

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

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

    // Work with the cache
    cache.put(42L, "The Answer!");
    cache.put(41L, "The wrong Answer!");
    cache.put(39L, "The other wrong Answer!");

    cacheManager.close();
}
 
Example #22
Source File: AbstractWriteBehindTestBase.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBatchedDeletedKeyReturnsNull() throws Exception {
  @SuppressWarnings("unchecked")
  CacheLoaderWriter<String, String> loaderWriter = mock(CacheLoaderWriter.class);
  when(loaderWriter.load("key")).thenReturn("value");
  CacheLoaderWriterProvider cacheLoaderWriterProvider = getMockedCacheLoaderWriterProvider(loaderWriter);

  try (CacheManager cacheManager = managerBuilder().using(cacheLoaderWriterProvider).build(true)) {
    Cache<String, String> testCache = cacheManager.createCache("testBatchedDeletedKeyReturnsNull", configurationBuilder()
      .withLoaderWriter(loaderWriter)
      .withService(newBatchedWriteBehindConfiguration(Long.MAX_VALUE, SECONDS, 2).build())
      .build());

    assertThat(testCache.get("key"), is("value"));

    testCache.remove("key");

    assertThat(testCache.get("key"), nullValue());
  }
}
 
Example #23
Source File: IntegrationConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testThreadPools() throws Exception {
  Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/thread-pools.xml"));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
  cacheManager.init();
  try {
    Cache<String, String> cache = cacheManager.createCache("testThreadPools", newCacheConfigurationBuilder(String.class, String.class, heap(10))
            .withService(new DefaultCacheLoaderWriterConfiguration(ThreadRememberingLoaderWriter.class))
            .withService(newUnBatchedWriteBehindConfiguration().useThreadPool("small"))
            .build());

    cache.put("foo", "bar");

    ThreadRememberingLoaderWriter.USED.acquireUninterruptibly();

    assertThat(ThreadRememberingLoaderWriter.LAST_SEEN_THREAD.getName(), containsString("[small]"));
  } finally {
    cacheManager.close();
  }
}
 
Example #24
Source File: StoreStatisticsTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void test2TiersStoreStatsAvailableInContextManager() throws Exception {
  try(CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("threeTieredCache",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
              newResourcePoolsBuilder()
                  .heap(1, MemoryUnit.MB)
                  .offheap(2, MemoryUnit.MB)
              )
      ).build(true)) {

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

    assertNull(cache.get(0L));

    long onHeapMisses = StoreStatisticsTest.<CachingTierOperationOutcomes.GetOrComputeIfAbsentOutcome>findStat(cache, "getOrComputeIfAbsent", "OnHeap")
      .count(CachingTierOperationOutcomes.GetOrComputeIfAbsentOutcome.MISS);
    assertThat(onHeapMisses, equalTo(1L));
    long offheapMisses = StoreStatisticsTest.<AuthoritativeTierOperationOutcomes.GetAndFaultOutcome>findStat(cache, "getAndFault", "OffHeap")
      .count(AuthoritativeTierOperationOutcomes.GetAndFaultOutcome.MISS);
    assertThat(offheapMisses, equalTo(1L));
  }
}
 
Example #25
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 #26
Source File: Tiering.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testNotShared() {
  // tag::notShared[]
  ResourcePools pool = ResourcePoolsBuilder.heap(10).build();

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("test-cache1", CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, String.class, pool))
    .withCache("test-cache2", CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, String.class, pool))
    .build(true);
  // end::notShared[]
}
 
Example #27
Source File: ThreadPoolsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultThreadPoolSucceedsWithoutConfig() throws Exception {
  PooledExecutionServiceConfiguration executionServiceConfiguration = new PooledExecutionServiceConfiguration();
  executionServiceConfiguration.addDefaultPool("dflt", 2, 4);
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .using(executionServiceConfiguration)
      .build(true);

  cacheManager.createCache("testCache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
          .build());

  cacheManager.close();
}
 
Example #28
Source File: EhcacheFactory.java    From pippo with Apache License 2.0 5 votes vote down vote up
public static CacheManager create(String path) {
    URL url = ClassLoader.getSystemResource(path);
    Configuration xmlConfig = new XmlConfiguration(url);
    CacheManager cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig);
    cacheManager.init();
    return cacheManager;
}
 
Example #29
Source File: DefaultManagementRegistryServiceTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCallOnInexistignContext() throws ExecutionException {
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
      .build();

  ManagementRegistryService managementRegistry = new DefaultManagementRegistryService(new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCM"));

  try(CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .withCache("aCache1", cacheConfiguration)
        .withCache("aCache2", cacheConfiguration)
        .using(managementRegistry)
        .build(true)) {

    Context inexisting = Context.empty()
        .with("cacheManagerName", "myCM2")
        .with("cacheName", "aCache2");

    ResultSet<? extends ContextualReturn<?>> results = managementRegistry.withCapability("ActionsCapability")
        .call("clear")
        .on(inexisting)
        .build()
        .execute();

    assertThat(results.size()).isEqualTo(1);
    assertThat(results.getSingleResult().hasExecuted()).isFalse();

    expectedException.expect(NoSuchElementException.class);
    results.getSingleResult().getValue();
  }
}
 
Example #30
Source File: BasicClusteredLoaderWriterTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test @SuppressWarnings("try")
public void testAllClientsNeedToHaveLoaderWriterConfigured() {
  TestCacheLoaderWriter loaderWriter = new TestCacheLoaderWriter();
  CacheConfiguration<Long, String> cacheConfiguration = getCacheConfiguration(loaderWriter);

  try (CacheManager cacheManager = CacheManagerBuilder
          .newCacheManagerBuilder()
          .with(cluster(CLUSTER_URI).autoCreate(c -> c))
          .withCache("cache-1", cacheConfiguration)
          .build(true)) {

    CacheConfiguration<Long, String> withoutLoaderWriter = newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder
        .newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).offheap(1, MemoryUnit.MB)
        .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)))
      .withResilienceStrategy(new ThrowingResilienceStrategy<>())
      .build();

    try (CacheManager anotherManager = CacheManagerBuilder
        .newCacheManagerBuilder()
        .with(cluster(CLUSTER_URI).autoCreate(c -> c))
        .withCache("cache-1", withoutLoaderWriter)
        .build(true)) {
    } catch (RuntimeException e) {
      assertThat(e.getCause().getCause().getCause().getCause(), instanceOf(CachePersistenceException.class));
      assertThat(e.getCause().getCause().getCause().getCause().getCause(), instanceOf(ClusterTierValidationException.class));
    }
  }
}