Java Code Examples for org.ehcache.Cache#get()

The following examples show how to use org.ehcache.Cache#get() . 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: 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 2
Source File: CacheCopierTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadWriteCopier() throws Exception {
  CacheConfiguration<Long, Person> cacheConfiguration = baseConfig
      .withService(new DefaultCopierConfiguration<>(PersonCopier.class, DefaultCopierConfiguration.Type.VALUE))
      .build();

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

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

  Person retrieved = cache.get(1l);
  assertNotSame(original, retrieved);
  assertThat(retrieved.name, equalTo("Bar"));
  assertThat(retrieved.age, equalTo(24));

  original.age = 56;
  retrieved = cache.get(1l);
  assertThat(retrieved.age, equalTo(24));

  assertNotSame(cache.get(1l), cache.get(1l));
}
 
Example 3
Source File: CacheCopierTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializingCopier() throws Exception {
  CacheConfiguration<Long, Person> cacheConfiguration = baseConfig
      .withService(new DefaultCopierConfiguration<>(SerializingCopier.<Person>asCopierClass(), DefaultCopierConfiguration.Type.VALUE))
      .withService(new DefaultSerializerConfiguration<>(PersonSerializer.class, DefaultSerializerConfiguration.Type.VALUE))
      .build();

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

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

  Person retrieved = cache.get(1l);
  assertNotSame(original, retrieved);
  assertThat(retrieved.name, equalTo("Bar"));
  assertThat(retrieved.age, equalTo(24));

  original.age = 56;
  retrieved = cache.get(1l);
  assertThat(retrieved.age, equalTo(24));

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

  Cache<Long, String> cache = cacheManager.createCache("onHeap", newCacheConfigurationBuilder(Long.class, String.class, heap(10))
              .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, 2, 0, 1, 0, 0);
  printSerializationCounters("Put OnHeap (create)");
  cache.get(42L);
  assertCounters(0, 0, 0, 0, 1, 0);
  printSerializationCounters("Get OnHeap");

  cache.put(42L, "Wrong ...");
  assertCounters(2, 2, 0, 1, 0, 0);
  printSerializationCounters("Put OnHeap (update)");
}
 
Example 9
Source File: CacheCopierTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCopyValueOnRead() throws Exception {
  CacheConfiguration<Long, Person> cacheConfiguration = baseConfig
      .withService(new DefaultCopierConfiguration<>(PersonOnReadCopier.class, DefaultCopierConfiguration.Type.VALUE))
      .build();

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

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

  Person retrieved = cache.get(1l);
  assertNotSame(original, retrieved);
  assertThat(retrieved.name, equalTo("Bar"));
  assertThat(retrieved.age, equalTo(24));

  original.age = 56;
  retrieved = cache.get(1l);
  assertThat(retrieved.age, equalTo(56));

  assertNotSame(cache.get(1l), cache.get(1l));
}
 
Example 10
Source File: XAGettingStarted.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonTransactionalAccess() throws Exception {
  // tag::testNonTransactionalAccess[]
  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);

  try {
    xaCache.get(1L); // <6>
    fail("expected XACacheException");
  } catch (XACacheException e) {
    // expected
  }

  cacheManager.close();
  transactionManager.shutdown();
  // end::testNonTransactionalAccess[]
}
 
Example 11
Source File: ManagementClusterConnectionTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void test_reconnection() throws Exception {
  long count = CLUSTER.get().getNmsService().readTopology().clientStream()
          .filter(client -> client.getName()
                  .startsWith("Ehcache:") && client.isManageable() && client.getTags()
                  .containsAll(Arrays.asList("webapp-1", "server-node-1")))
          .count();

  Assert.assertThat(count, Matchers.equalTo(1L));

  String instanceId = getInstanceId();

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

  Cache<String, String> cache = cacheManager.getCache("dedicated-cache-1", String.class, String.class);
  String initiate_reconnect = cache.get("initiate reconnect");

  assertThat(initiate_reconnect, Matchers.nullValue());

  assertThat(() -> {
    try {
      return CLUSTER.get().getNmsService().readTopology().clientStream()
                .filter(client -> client.getName()
                        .startsWith("Ehcache:") && client.isManageable() && client.getTags()
                        .containsAll(Arrays.asList("webapp-1", "server-node-1")))
                .count();
    } catch (Exception e) {
      throw new AssertionError(e);
    }
  }, within(Duration.ofSeconds(30)).is(1L));
  assertThat(getInstanceId(), equalTo(instanceId));
}
 
Example 12
Source File: TranslateEhcacheManager.java    From sagacity-sqltoy with Apache License 2.0 5 votes vote down vote up
@Override
public HashMap<String, Object[]> getCache(String cacheName, String cacheKey) {
	if (cacheManager == null) {
		return null;
	}
	Cache<String, HashMap> cache = cacheManager.getCache(cacheName, String.class, HashMap.class);
	if (cache == null) {
		return null;
	}
	Object cacheValue = cache.get(StringUtil.isNotBlank(cacheKey) ? cacheKey : cacheName);
	if (cacheValue != null) {
		return (HashMap<String, Object[]>) cacheValue;
	}
	return null;
}
 
Example 13
Source File: SyncService.java    From moon-api-gateway with MIT License 5 votes vote down vote up
/**
 * Delete the allowed ip for the application.
 *
 * @param appId The Application Id.
 * @param requestIps The ip list to delete.
 * @return Whether the operation was successful. Not yet applied.
 */
private boolean deleteWhitelistIp(int appId, List<String> requestIps) {
    Cache<Integer, AppInfo> appInfoCaches = apiExposeSpec.getAppInfoCache();
    AppInfo appInfo = appInfoCaches.get(appId);
    requestIps.forEach(ip -> appInfo.getAppIpAcl().remove(ip));
    appInfoCaches.replace(appInfo.getAppId(), appInfo);

    return true;
}
 
Example 14
Source File: EHCache3Manager.java    From javalite with Apache License 2.0 5 votes vote down vote up
@Override
public Object getCache(String group, String key) {
    try {
        Cache<String, Object> c = getCacheForGroupOrCreateIt(group);
        return c.get(key);
    } catch (Exception e) {
        LOGGER.warn("{}", e, e);
        return null;
    }
}
 
Example 15
Source File: ByteSizedOnHeapOsgiTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
public static void testByteSizedOnHeapInOsgi() {
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("myCache", newCacheConfigurationBuilder(Long.class, String.class, newResourcePoolsBuilder().heap(10, MemoryUnit.KB))
      .build())
    .build(true);

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

  cache.put(42L, "I am out of heap!!");

  cache.get(42L);
}
 
Example 16
Source File: TerminatedServerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * If the server goes down, the client should not freeze on a server call. It should timeout and answer using
 * the resilience strategy. Whatever the number of calls is done afterwards.
 *
 * @throws Exception
 */
@Test
public void testTerminationFreezesTheClient() throws Exception {
  Duration readOperationTimeout = Duration.ofMillis(100);

  try(PersistentCacheManager cacheManager =
        CacheManagerBuilder.newCacheManagerBuilder()
          .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER.get().getConnectionURI().resolve("/").resolve(testName.getMethodName()))
            .timeouts(TimeoutsBuilder.timeouts()
              .read(readOperationTimeout))
            .autoCreate(server -> server.defaultServerResource("primary-server-resource")))
          .withCache("simple-cache",
            CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
              ResourcePoolsBuilder.newResourcePoolsBuilder()
                .with(ClusteredResourcePoolBuilder.clusteredDedicated(4, MemoryUnit.MB))))
          .build(true)) {

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

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

    // Fill the inflight queue and check that we wait no longer than the read timeout
    for (int i = 0; i < CLIENT_MAX_PENDING_REQUESTS; i++) {
      cache.get(1L);
    }

    // The resilience strategy will pick it up and not exception is thrown
    new TimeLimitedTask<Void>(readOperationTimeout.multipliedBy(2)) { // I multiply by 2 to let some room after the expected timeout
      @Override
      Void runTask() {
        cache.get(1L); // the call that could block
        return null;
      }
    }.run();

  } catch(StateTransitionException e) {
    // On the cacheManager.close(), it waits for the lease to expire and then throw this exception
  }
}
 
Example 17
Source File: DefaultManagementRegistryServiceTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void testCanGetStats() {
  String queryStatisticName = "Cache:HitCount";

  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 context1 = Context.empty()
      .with("cacheManagerName", "myCM")
      .with("cacheName", "aCache1");

    Context context2 = Context.empty()
      .with("cacheManagerName", "myCM")
      .with("cacheName", "aCache2");

    Cache<Long, String> cache1 = cacheManager.getCache("aCache1", Long.class, String.class);
    Cache<Long, String> cache2 = cacheManager.getCache("aCache2", Long.class, String.class);

    cache1.put(1L, "one");
    cache2.put(3L, "three");

    cache1.get(1L);
    cache1.get(2L);
    cache2.get(3L);
    cache2.get(4L);

    Builder builder1 = managementRegistry.withCapability("StatisticsCapability")
      .queryStatistic(queryStatisticName)
      .on(context1);

    ContextualStatistics counters = getResultSet(builder1, context1, null, queryStatisticName).getResult(context1);
    Number counterHistory1 = counters.<Number>getLatestSampleValue(queryStatisticName).get();

    assertThat(counters.size()).isEqualTo(1);
    assertThat(counterHistory1.longValue()).isEqualTo(1L);

    Builder builder2 = managementRegistry.withCapability("StatisticsCapability")
      .queryStatistic(queryStatisticName)
      .on(context1)
      .on(context2);
    ResultSet<ContextualStatistics> allCounters = getResultSet(builder2, context1, context2, queryStatisticName);

    assertThat(allCounters.size()).isEqualTo(2);
    assertThat(allCounters.getResult(context1).size()).isEqualTo(1);
    assertThat(allCounters.getResult(context2).size()).isEqualTo(1);

    assertThat(allCounters.getResult(context1).getLatestSampleValue(queryStatisticName).get()).isEqualTo(1L);
    assertThat(allCounters.getResult(context2).getLatestSampleValue(queryStatisticName).get()).isEqualTo(1L);
  }
}
 
Example 18
Source File: ClusteredStatisticsCountTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void countTest() throws Exception {
  sendManagementCallOnClientToCollectStats();

  Cache<String, String> cache = cacheManager.getCache("dedicated-cache-1", String.class, String.class);
  cache.put("one", "val1");
  cache.put("two", "val2");

  cache.get("one");   //hit
  cache.get("two");   //hit

  cache.get("three"); //miss
  cache.get("four");  //miss


  long cacheHitCount = 0;
  long clusteredHitCount = 0;
  long cacheMissCount = 0;
  long clusteredMissCount = 0;

  // it could be several seconds before the sampled stats could become available
  // let's try until we find the correct values
  do {

    // get the stats (we are getting the primitive counter, not the sample history)
    List<ContextualStatistics> stats = waitForNextStats();
    for (ContextualStatistics stat : stats) {
      if (stat.getContext().contains("cacheName") && stat.getContext().get("cacheName").equals("dedicated-cache-1")) {

        // please leave it there - it's really useful to see what's coming
        /*
        System.out.println("stats:");

        Set<Map.Entry<String, Statistic<?>>> entries = stat.getStatistics().entrySet();
        for (Map.Entry<String, Statistic<?>> entry : entries) {
          System.out.println(" - " + entry.getKey() + " : " + entry.getValue());
        }*/

        cacheHitCount = stat.<Long>getLatestSampleValue("Cache:HitCount").get();
        clusteredHitCount = stat.<Long>getLatestSampleValue("Clustered:HitCount").get();
        clusteredMissCount = stat.<Long>getLatestSampleValue("Clustered:MissCount").get();
        cacheMissCount = stat.<Long>getLatestSampleValue("Cache:MissCount").get();
      }
    }
  } while(!Thread.currentThread().isInterrupted() &&
          ((cacheHitCount != CACHE_HIT_COUNT) || (clusteredHitCount != CLUSTERED_HIT_COUNT) ||
          (cacheMissCount != CACHE_MISS_COUNT) || (clusteredMissCount != CLUSTERED_MISS_COUNT)));


  Assert.assertThat(cacheHitCount,is(CACHE_HIT_COUNT));
  Assert.assertThat(clusteredHitCount,is(CLUSTERED_HIT_COUNT));
  Assert.assertThat(cacheMissCount,is(CACHE_MISS_COUNT));
  Assert.assertThat(clusteredMissCount,is(CLUSTERED_MISS_COUNT));

}
 
Example 19
Source File: ManagementTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void usingManagementRegistry() throws Exception {
  // tag::usingManagementRegistry[]

  CacheManager cacheManager = null;
  try {
    DefaultManagementRegistryConfiguration registryConfiguration = new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCacheManager1"); // <1>
    ManagementRegistryService managementRegistry = new DefaultManagementRegistryService(registryConfiguration); // <2>

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

    cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .withCache("myCache", cacheConfiguration)
        .using(managementRegistry) // <3>
        .build(true);

    Object o = managementRegistry.withCapability("StatisticCollectorCapability")
      .call("updateCollectedStatistics",
        new Parameter("StatisticsCapability"),
        new Parameter(Arrays.asList("Cache:HitCount", "Cache:MissCount"), Collection.class.getName()))
      .on(Context.create("cacheManagerName", "myCacheManager1"))
      .build()
      .execute()
      .getSingleResult();
    System.out.println(o);

    Cache<Long, String> aCache = cacheManager.getCache("myCache", Long.class, String.class);
    aCache.put(1L, "one");
    aCache.put(0L, "zero");
    aCache.get(1L); // <4>
    aCache.get(0L); // <4>
    aCache.get(0L);
    aCache.get(0L);

    Context context = StatsUtil.createContext(managementRegistry); // <5>

    StatisticQuery query = managementRegistry.withCapability("StatisticsCapability") // <6>
        .queryStatistic("Cache:HitCount")
        .on(context)
        .build();

    ResultSet<ContextualStatistics> counters = query.execute();

    ContextualStatistics statisticsContext = counters.getResult(context);

    Assert.assertThat(counters.size(), Matchers.is(1));
  }
  finally {
    if(cacheManager != null) cacheManager.close();
  }
  // end::usingManagementRegistry[]
}
 
Example 20
Source File: ManagementTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
public void managingMultipleCacheManagers() throws Exception {
  // tag::managingMultipleCacheManagers[]
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))
      .build();

  CacheManager cacheManager1 = null;
  CacheManager cacheManager2 = null;
  try {
    SharedManagementService sharedManagementService = new DefaultSharedManagementService(); // <1>
    cacheManager1 = CacheManagerBuilder.newCacheManagerBuilder()
        .withCache("aCache", cacheConfiguration)
        .using(new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCacheManager-1"))
        .using(sharedManagementService) // <2>
        .build(true);

    cacheManager2 = CacheManagerBuilder.newCacheManagerBuilder()
        .withCache("aCache", cacheConfiguration)
        .using(new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCacheManager-2"))
        .using(sharedManagementService) // <3>
        .build(true);

    Context context1 = Context.empty()
      .with("cacheManagerName", "myCacheManager-1")
      .with("cacheName", "aCache");

    Context context2 = Context.empty()
      .with("cacheManagerName", "myCacheManager-2")
      .with("cacheName", "aCache");

    Cache<Long, String> cache = cacheManager1.getCache("aCache", Long.class, String.class);
    cache.get(1L);//cache miss
    cache.get(2L);//cache miss

    StatisticQuery query = sharedManagementService.withCapability("StatisticsCapability")
      .queryStatistic("Cache:MissCount")
      .on(context1)
      .on(context2)
      .build();

    long val = 0;
    // it could be several seconds before the sampled stats could become available
    // let's try until we find the correct value : 2
    do {
      ResultSet<ContextualStatistics> counters = query.execute();

      ContextualStatistics statisticsContext1 = counters.getResult(context1);

      Long counterContext1 = statisticsContext1.<Long>getLatestSampleValue("Cache:MissCount").get();

      // miss count is a sampled stat, for example its values could be [0,1,2].
      // In the present case, only the last value is important to us , the cache was eventually missed 2 times
      val = counterContext1.longValue();
    } while(val != 2);
  }
  finally {
    if(cacheManager2 != null) cacheManager2.close();
    if(cacheManager1 != null) cacheManager1.close();
  }

  // end::managingMultipleCacheManagers[]
}