org.ehcache.Cache Java Examples

The following examples show how to use org.ehcache.Cache. 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: CacheManagerDestroyTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseCacheManagerMultipleClients() {
  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)) {

    Cache<Long, String> cache = persistentCacheManager1.getCache("test", Long.class, String.class);
    cache.put(1L, "One");

    assertThat(cache.get(1L), is("One"));

    persistentCacheManager1.close();
    assertThat(persistentCacheManager1.getStatus(), is(Status.UNINITIALIZED));

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

    assertThat(cache2.get(1L), is("One"));
  }
}
 
Example #2
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 #3
Source File: CacheCopierTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testIdentityCopier() throws Exception {
  CacheConfiguration<Long, Person> cacheConfiguration = baseConfig.build();

  Cache<Long, Person> cache = cacheManager.createCache("cache", cacheConfiguration);

  Person original = new Person("Bar", 24);
  cache.put(1l, original);

  Person retrieved = cache.get(1l);
  assertSame(original, retrieved);

  original.age = 25;
  retrieved = cache.get(1l);
  assertSame(original, retrieved);

  assertSame(cache.get(1l), cache.get(1l));
}
 
Example #4
Source File: CacheManagerDestroyTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseCacheManagerSingleClient() {
  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);

  persistentCacheManager1.close();

  persistentCacheManager1.init();

  Cache<Long, String> cache = persistentCacheManager1.getCache("test", Long.class, String.class);
  cache.put(1L, "One");

  assertThat(cache.get(1L), is("One"));

  persistentCacheManager1.close();
}
 
Example #5
Source File: BasicClusteredLoaderWriterTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicClusteredCacheLoaderWriter() {

  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)) {

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

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

    assertThat(cache.get(1L), is("1"));

    assertThat(loaderWriter.storeMap.get(1L), is("1"));
  }
}
 
Example #6
Source File: XACacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
private void replace2ArgsAssertions(BitronixTransactionManager transactionManager, Cache<Long, String> txCache1) throws Exception {
  transactionManager.begin();
  {
    assertThat(txCache1.replace(1L, "one"), is(nullValue()));
    txCache1.put(1L, "un");
    assertThat(txCache1.replace(1L, "eins"), equalTo("un"));
  }
  transactionManager.commit();

  assertMapping(transactionManager, txCache1, 1L, "eins");

  transactionManager.begin();
  {
    assertThat(txCache1.replace(1L, "een"), equalTo("eins"));
    txCache1.put(1L, "un");
    assertThat(txCache1.replace(1L, "een"), equalTo("un"));
    txCache1.remove(1L);
    assertThat(txCache1.replace(1L, "one"), is(nullValue()));
    assertThat(txCache1.get(1L), is(nullValue()));
  }
  transactionManager.commit();

  assertMapping(transactionManager, txCache1, 1L, null);
}
 
Example #7
Source File: ClusteredOsgiTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
public static void testXmlClusteredCache(OsgiTestUtils.Cluster cluster) throws Exception {
  File config = cluster.getWorkingArea().resolve("ehcache.xml").toFile();

  Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(TestMethods.class.getResourceAsStream("ehcache-clustered-osgi.xml"));
  XPath xpath = XPathFactory.newInstance().newXPath();
  Node clusterUriAttribute = (Node) xpath.evaluate("//config/service/cluster/connection/@url", doc, XPathConstants.NODE);
  clusterUriAttribute.setTextContent(cluster.getConnectionUri().toString() + "/cache-manager");
  Transformer xformer = TransformerFactory.newInstance().newTransformer();
  xformer.transform(new DOMSource(doc), new StreamResult(config));


  try (PersistentCacheManager cacheManager = (PersistentCacheManager) CacheManagerBuilder.newCacheManager(
    new XmlConfiguration(config.toURI().toURL(), TestMethods.class.getClassLoader())
  )) {
    cacheManager.init();

    final Cache<Long, Person> cache = cacheManager.getCache("clustered-cache", Long.class, Person.class);

    cache.put(1L, new Person("Brian"));
    assertThat(cache.get(1L).name, is("Brian"));
  }
}
 
Example #8
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 #9
Source File: ClusteredProgrammatic.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");

  URI uri = create("terracotta://localhost:9410/clustered");
  try (CacheManager cacheManager = newCacheManagerBuilder()
          .with(cluster(uri).autoCreate().defaultServerResource("default-resource"))
          .withCache("basicCache",
                  newCacheConfigurationBuilder(Long.class, String.class,
                          heap(100).offheap(1, MB).with(clusteredDedicated(5, MB))))
          .build(true)) {
    Cache<Long, String> basicCache = cacheManager.getCache("basicCache", Long.class, String.class);

    LOGGER.info("Putting to cache");
    basicCache.put(1L, "da one!");

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

  LOGGER.info("Exiting");
}
 
Example #10
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 #11
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 #12
Source File: ClusteredStoreTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleChainRequiresResolution() throws StoreAccessException {

  store.put(~1L, "bar");
  store.put(1L, "foo");
  store.remove(~1L);

  Store.Iterator<Cache.Entry<Long, Store.ValueHolder<String>>> iterator = store.iterator();

  assertThat(iterator.hasNext(), is(true));
  assertThat(iterator.next(), isEntry(1L, "foo"));
  assertThat(iterator.hasNext(), is(false));
  try {
    iterator.next();
    fail("Expected NoSuchElementException");
  } catch (NoSuchElementException e) {
    //expected
  }
}
 
Example #13
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 #14
Source File: TransactionalOsgiTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
public static void testProgrammaticConfiguration() throws Exception {
  BitronixTransactionManager transactionManager = getTransactionManager();

  try (CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withClassLoader(TestMethods.class.getClassLoader())
    .using(new LookupTransactionManagerProviderConfiguration(BitronixTransactionManagerLookup.class))
    .withCache("xaCache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
      .withService(new XAStoreConfiguration("xaCache")).build()).build(true)) {

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

    transactionManager.begin();
    try {
      xaCache.put(1L, "one");
    } catch (Throwable t) {
      transactionManager.rollback();
    }
    transactionManager.commit();
  }
  transactionManager.shutdown();
}
 
Example #15
Source File: ClusteredCacheExpirationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNoExpirationPropagatedToHigherTiers() throws CachePersistenceException {
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = cacheManagerBuilder(ExpiryPolicyBuilder.noExpiration());

  try(PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) {

    Map<String, TierStatistics> tierStatistics = statisticsService.getCacheStatistics(CLUSTERED_CACHE).getTierStatistics();
    TierStatistics onheap = tierStatistics.get("OnHeap");
    TierStatistics offheap = tierStatistics.get("OffHeap");

    Cache<Long, String> cache = cacheManager.getCache(CLUSTERED_CACHE, Long.class, String.class);
    for (long i = 0; i < 30; i++) {
      cache.put(i, "value"); // store on the cluster
      cache.get(i); // push it up on heap and offheap tier
    }

    assertThat(onheap.getMappings()).isEqualTo(10);
    assertThat(offheap.getMappings()).isEqualTo(20);
  }
}
 
Example #16
Source File: StoreStatisticsTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void test1TierStoreStatsAvailableInContextManager() throws Exception {
  try(CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("threeTieredCache",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(1))
            .withService(new StoreStatisticsConfiguration(true)) // explicitly enable statistics
      ).build(true)) {

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

    assertNull(cache.get(0L));

    long onHeapMisses = StoreStatisticsTest.<StoreOperationOutcomes.GetOutcome>findStat(cache, "get", "OnHeap").count(StoreOperationOutcomes.GetOutcome.MISS);
    assertThat(onHeapMisses, equalTo(1L));
  }
}
 
Example #17
Source File: StoreIteratorHasNextTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@SPITest
public void hasNext()
    throws IllegalAccessException, InstantiationException, StoreAccessException, LegalSPITesterException {
  kvStore = factory.newStore();

  int nbElements = 3;
  for (int i = 0; i < nbElements; i++) {
    kvStore.put(factory.createKey(1), factory.createValue(1));
  }

  Store.Iterator<Cache.Entry<K, Store.ValueHolder<V>>> iterator = kvStore.iterator();

  for (int i = 0; i < nbElements; i++) {
    assertThat(iterator.hasNext(), is(true));
  }
}
 
Example #18
Source File: APIExposeSpecification.java    From moon-api-gateway with MIT License 5 votes vote down vote up
/**
 * A method that takes a cache with path information that identifies which api the client requested.
 * The path information is contained in a pattern for regex operations.
 * The regex operation takes a lot of time, so keep it separate by http method.
 *
 * @param requestMethodType The http method type requested by the client.
 * @return EhCache Object about apiId-routingPathPattern
 */
public Cache<Integer, Pattern> getRoutingPathCache(MethodType requestMethodType) {
    if (MethodType.GET == requestMethodType) {
        return apiMatchGet;
    } else if (MethodType.POST == requestMethodType) {
        return apiMatchPost;
    } else if (MethodType.PUT == requestMethodType) {
        return apiMatchPut;
    } else if (MethodType.DELETE == requestMethodType) {
        return apiMatchDelete;
    }
    return null;
}
 
Example #19
Source File: SyncService.java    From moon-api-gateway with MIT License 5 votes vote down vote up
/**
 * Clears the application information from the cache.
 *
 * @param appInfo Application information object. The apikey and appId variables are required.
 * @return Whether the operation was successful. Not yet applied.
 */
private boolean deleteApp(AppInfo appInfo) {
    Cache<String, Integer> appDistinction = apiExposeSpec.getAppDistinctionCache();
    appDistinction.remove(appInfo.getApiKey());

    Cache<Integer, AppInfo> appInfoCaches = apiExposeSpec.getAppInfoCache();
    appInfoCaches.remove(appInfo.getAppId());

    return true;
}
 
Example #20
Source File: XACacheTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private void remove2ArgsAssertions(BitronixTransactionManager transactionManager, Cache<Long, String> txCache1) throws Exception {
  transactionManager.begin();
  {
    assertThat(txCache1.remove(1L, "one"), is(false));
    assertThat(txCache1.putIfAbsent(1L, "un"), is(nullValue()));
    assertThat(txCache1.remove(1L, "one"), is(false));
    assertThat(txCache1.remove(1L, "un"), is(true));
    assertThat(txCache1.remove(1L, "un"), is(false));
  }
  transactionManager.commit();

  assertMapping(transactionManager, txCache1, 1L, null);

  transactionManager.begin();
  {
    txCache1.put(1L, "one");
  }
  transactionManager.commit();

  assertMapping(transactionManager, txCache1, 1L, "one");

  transactionManager.begin();
  {
    assertThat(txCache1.remove(1L, "un"), is(false));
    assertThat(txCache1.remove(1L, "one"), is(true));
    assertThat(txCache1.remove(1L, "one"), is(false));
    assertThat(txCache1.putIfAbsent(1L, "un"), is(nullValue()));
    assertThat(txCache1.remove(1L, "one"), is(false));
    assertThat(txCache1.remove(1L, "un"), is(true));
  }
  transactionManager.commit();

  assertMapping(transactionManager, txCache1, 1L, null);
}
 
Example #21
Source File: BasicClusteredCacheOpsReplicationWithMultipleClientsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test(timeout=180000)
public void testClear() throws Exception {
  List<Cache<Long, BlobValue>> caches = new ArrayList<>();
  caches.add(cache1);
  caches.add(cache2);

  Map<Long, BlobValue> entriesMap = new HashMap<>();

  Random random = new Random();
  LongStream longStream = random.longs(1000);

  longStream.forEach(x -> entriesMap.put(x, new BlobValue()));
  caches.forEach(cache -> cache.putAll(entriesMap));

  Set<Long> keySet = entriesMap.keySet();

  Set<Long> readKeysByCache2BeforeFailOver = new HashSet<>();
  keySet.forEach(x -> {
    if (cache2.get(x) != null) {
      readKeysByCache2BeforeFailOver.add(x);
    }
  });

  cache1.clear();

  CLUSTER.getClusterControl().waitForRunningPassivesInStandby();
  CLUSTER.getClusterControl().terminateActive();

  if (cacheConsistency == Consistency.STRONG) {
    readKeysByCache2BeforeFailOver.forEach(x -> assertThat(cache2.get(x), nullValue()));
  } else {
    readKeysByCache2BeforeFailOver.forEach(x -> assertThat(cache1.get(x), nullValue()));
  }

}
 
Example #22
Source File: SimpleOsgiTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
public static void testCustomCopier() {
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("myCache", newCacheConfigurationBuilder(Long.class, String.class, heap(10))
      .withService(new DefaultCopierConfiguration<>(StringCopier.class, DefaultCopierConfiguration.Type.VALUE))
      .withClassLoader(TestMethods.class.getClassLoader())
      .build())
    .build(true);

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

  cache.put(42L, "What's the question again?");
  cache.get(42L);
}
 
Example #23
Source File: AbstractWriteBehindTestBase.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnBatchedWriteBehindBlocksWhenFull() throws Exception {
  final Semaphore gate = new Semaphore(0);
  @SuppressWarnings("unchecked")
  CacheLoaderWriter<String, String> loaderWriter = mock(CacheLoaderWriter.class);
  doAnswer(invocation -> {
    gate.acquire();
    return null;
  }).when(loaderWriter).write(anyString(), anyString());

  CacheLoaderWriterProvider cacheLoaderWriterProvider = getMockedCacheLoaderWriterProvider(loaderWriter);

  try (CacheManager cacheManager = managerBuilder().using(cacheLoaderWriterProvider).build(true)) {
    final Cache<String, String> testCache = cacheManager.createCache("testUnBatchedWriteBehindBlocksWhenFull", configurationBuilder()
      .withLoaderWriter(loaderWriter)
      .withService(newUnBatchedWriteBehindConfiguration().queueSize(1).build())
      .build());

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

    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
      Future<?> blockedPut = executor.submit(() -> testCache.put("key3", "value"));

      try {
        blockedPut.get(100, MILLISECONDS);
        fail("Expected TimeoutException");
      } catch (TimeoutException e) {
        //expected
      }
      gate.release();
      blockedPut.get(10, SECONDS);
      gate.release(Integer.MAX_VALUE);
    } finally {
      executor.shutdown();
    }
  }
}
 
Example #24
Source File: XAGettingStarted.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleXACache() throws Exception {
  // tag::testSimpleXACache[]
  BitronixTransactionManager transactionManager =
      TransactionManagerServices.getTransactionManager(); // <1>

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .using(new LookupTransactionManagerProviderConfiguration(BitronixTransactionManagerLookup.class)) // <2>
      .withCache("xaCache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, // <3>
                                                          ResourcePoolsBuilder.heap(10)) // <4>
          .withService(new XAStoreConfiguration("xaCache")) // <5>
          .build()
      )
      .build(true);

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

  transactionManager.begin(); // <6>
  {
    xaCache.put(1L, "one"); // <7>
  }
  transactionManager.commit(); // <8>

  cacheManager.close();
  transactionManager.shutdown();
  // end::testSimpleXACache[]
}
 
Example #25
Source File: StoreStatisticsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void test1TierStoreStatsAvailableInContextManager_disabledByDefault() throws Exception {
  try(CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("threeTieredCache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(1))
    ).build(true)) {

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

    assertNull(cache.get(0L));

    assertNull("Statistics are disabled so nothing is expected here", StoreStatisticsTest.<StoreOperationOutcomes.GetOutcome>findStat(cache, "get", "OnHeap"));
  }
}
 
Example #26
Source File: BasicClusteredCacheOpsReplicationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCRUD() throws Exception {
  List<Cache<Long, String>> caches = new ArrayList<>();
  caches.add(cacheOne);
  caches.add(cacheTwo);
  caches.forEach(x -> {
    x.put(1L, "The one");
    x.put(2L, "The two");
    x.put(1L, "Another one");
    x.put(3L, "The three");
    x.put(4L, "The four");
    assertThat(x.get(1L), equalTo("Another one"));
    assertThat(x.get(2L), equalTo("The two"));
    assertThat(x.get(3L), equalTo("The three"));
    x.remove(4L);
  });

  CLUSTER.getClusterControl().waitForRunningPassivesInStandby();
  CLUSTER.getClusterControl().terminateActive();

  caches.forEach(x -> {
    assertThat(x.get(1L), equalTo("Another one"));
    assertThat(x.get(2L), equalTo("The two"));
    assertThat(x.get(3L), equalTo("The three"));
    assertThat(x.get(4L), nullValue());
  });
}
 
Example #27
Source File: Tiering.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void updateResourcesAtRuntime() throws InterruptedException {
  ListenerObject listener = new ListenerObject();
  CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
    .newEventListenerConfiguration(listener, EventType.EVICTED).unordered().synchronous();

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

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

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

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

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

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

  cacheManager.close();
}
 
Example #28
Source File: StoreStatisticsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void test3TiersStoreStatsAvailableInContextManager() throws Exception {
  try(PersistentCacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .with(new CacheManagerPersistenceConfiguration(new File(getStoragePath(), "StoreStatisticsTest")))
      .withCache("threeTieredCache",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
              newResourcePoolsBuilder()
                  .heap(1, MemoryUnit.MB)
                  .offheap(2, MemoryUnit.MB)
                  .disk(5, 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.<LowerCachingTierOperationsOutcome.GetAndRemoveOutcome>findStat(cache, "getAndRemove", "OffHeap")
      .count(LowerCachingTierOperationsOutcome.GetAndRemoveOutcome.MISS);
    assertThat(offHeapMisses, equalTo(1L));
    long diskMisses = StoreStatisticsTest.<AuthoritativeTierOperationOutcomes.GetAndFaultOutcome>findStat(cache, "getAndFault", "Disk").count(AuthoritativeTierOperationOutcomes.GetAndFaultOutcome.MISS);
    assertThat(diskMisses, equalTo(1L));
  }
}
 
Example #29
Source File: SimpleEhcacheTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleReplace() throws Exception {
  Cache<Number, CharSequence> testCache = cacheManager.createCache("testCache", newCacheConfigurationBuilder(Number.class, CharSequence.class, heap(10)));

  testCache.put(1, "one");

  assertThat(testCache.replace(1, "one_"), Matchers.<CharSequence>equalTo("one"));
  assertThat(testCache.get(1), Matchers.<CharSequence>equalTo("one_"));
  assertThat(testCache.replace(2, "two_"), is(nullValue()));
}
 
Example #30
Source File: BasicClusteredCacheOpsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void basicCacheCAS() throws Exception {
  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
      newCacheManagerBuilder()
          .with(cluster(CLUSTER.getConnectionURI().resolve("/cas-cm")).autoCreate(c -> c))
          .withCache("clustered-cache", newCacheConfigurationBuilder(Long.class, String.class,
              ResourcePoolsBuilder.newResourcePoolsBuilder().heap(100, EntryUnit.ENTRIES)
                  .with(ClusteredResourcePoolBuilder.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(cache1.putIfAbsent(1L, "one"), nullValue());
      assertThat(cache2.putIfAbsent(1L, "another one"), is("one"));
      assertThat(cache2.remove(1L, "another one"), is(false));
      assertThat(cache1.replace(1L, "another one"), is("one"));
      assertThat(cache2.replace(1L, "another one", "yet another one"), is(true));
      assertThat(cache1.remove(1L, "yet another one"), is(true));
      assertThat(cache2.replace(1L, "one"), nullValue());
      assertThat(cache1.replace(1L, "another one", "yet another one"), is(false));
    }
  }
}