Java Code Examples for org.ehcache.CacheManager#getCache()
The following examples show how to use
org.ehcache.CacheManager#getCache() .
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: TestEhcache.java From elastic-rabbitmq with MIT License | 6 votes |
@Test public void testTem() { CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("preConfigured", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))) .build(); cacheManager.init(); Cache<Long, String> preConfigured = cacheManager.getCache("preConfigured", Long.class, String.class); Cache<Long, String> myCache = cacheManager.createCache("myCache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))); myCache.put(1L, "da one!"); myCache.putIfAbsent(0L, "ee"); String value = myCache.get(1L); System.out.println("Value is " + value); cacheManager.removeCache("preConfigured"); cacheManager.close(); }
Example 2
Source File: GettingStarted.java From ehcache3 with Apache License 2.0 | 6 votes |
@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 3
Source File: IntegrationConfigurationTest.java From ehcache3 with Apache License 2.0 | 6 votes |
@Test public void testCopiers() throws Exception { Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/cache-copiers.xml")); final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration); cacheManager.init(); Cache<Description, Person> bar = cacheManager.getCache("bar", Description.class, Person.class); Description desc = new Description(1234, "foo"); Person person = new Person("Bar", 24); bar.put(desc, person); assertEquals(person, bar.get(desc)); assertNotSame(person, bar.get(desc)); Cache<Long, Person> baz = cacheManager.getCache("baz", Long.class, Person.class); baz.put(1L, person); assertEquals(person, baz.get(1L)); assertNotSame(person, baz.get(1L)); Employee empl = new Employee(1234, "foo", 23); Cache<Long, Employee> bak = cacheManager.getCache("bak", Long.class, Employee.class); bak.put(1L, empl); assertSame(empl, bak.get(1L)); cacheManager.close(); }
Example 4
Source File: IntegrationConfigurationTest.java From ehcache3 with Apache License 2.0 | 6 votes |
@Test public void testCacheEventListenerWithMultipleListener() throws Exception { Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/ehcache-multipleCacheEventListener.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); resetValues(); cache.put(10, "dog"); assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.CREATED)); assertThat(TestSecondCacheEventListener.SECOND_LISTENER_FIRED_EVENT, is(nullValue())); resetValues(); cache.put(10, "cat"); assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.UPDATED)); assertThat(TestSecondCacheEventListener.SECOND_LISTENER_FIRED_EVENT.getType(), is(EventType.UPDATED)); resetValues(); cache.remove(10); assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.REMOVED)); assertThat(TestSecondCacheEventListener.SECOND_LISTENER_FIRED_EVENT.getType(), is(EventType.REMOVED)); }
Example 5
Source File: EventNotificationTest.java From ehcache3 with Apache License 2.0 | 6 votes |
@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 6
Source File: EhcacheBulkMethodsITest.java From ehcache3 with Apache License 2.0 | 5 votes |
@Test public void testGetAll_cache_loader_throws_exception() throws Exception { CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class, heap(100)); CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class); CacheLoaderWriter cacheLoaderWriter = mock(CacheLoaderWriter.class); when(cacheLoaderWriter.load(ArgumentMatchers.any())).thenThrow(new RuntimeException("We should not have called .load() but .loadAll()")); when(cacheLoaderWriter.loadAll(ArgumentMatchers.any(Iterable.class))).thenThrow(new Exception("Simulating an exception from the cache loader")); when(cacheLoaderWriterProvider.createCacheLoaderWriter(anyString(), ArgumentMatchers.any(CacheConfiguration.class))).thenReturn(cacheLoaderWriter); CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider); CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.withLoaderWriter(cacheLoaderWriter).build(); CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true); Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class); Set<String> fewKeysSet = new HashSet<String>() { { add("key0"); add("key2"); } }; // the call to getAll try { myCache.getAll(fewKeysSet); fail(); } catch (BulkCacheLoadingException bcwe) { // since onHeapStore.bulkComputeIfAbsent sends batches of 1 element, assertThat(bcwe.getFailures().size(), is(2)); assertThat(bcwe.getSuccesses().size(), is(0)); } }
Example 7
Source File: EhcacheBulkMethodsITest.java From ehcache3 with Apache License 2.0 | 5 votes |
@Test public void testPutAll_with_cache_writer_that_throws_exception() throws Exception { CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class, heap(100)); CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class); CacheLoaderWriter cacheLoaderWriterThatThrows = mock(CacheLoaderWriter.class); doThrow(new RuntimeException("We should not have called .write() but .writeAll()")).when(cacheLoaderWriterThatThrows).write(ArgumentMatchers .any(), ArgumentMatchers.any()); doThrow(new Exception("Simulating an exception from the cache writer")).when(cacheLoaderWriterThatThrows).writeAll(ArgumentMatchers.any(Iterable.class)); when(cacheLoaderWriterProvider.createCacheLoaderWriter(anyString(), ArgumentMatchers.any(CacheConfiguration.class))).thenReturn(cacheLoaderWriterThatThrows); CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider); CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.withLoaderWriter(cacheLoaderWriterThatThrows).build(); 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 try { myCache.putAll(stringStringHashMap); fail(); } catch (BulkCacheWritingException bcwe) { assertThat(bcwe.getFailures().size(), is(3)); assertThat(bcwe.getSuccesses().size(), is(0)); } }
Example 8
Source File: EhcacheBulkMethodsITest.java From ehcache3 with Apache License 2.0 | 5 votes |
@Test public void testRemoveAll_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); for (int i = 0; i < 3; i++) { myCache.put("key" + i, "value" + i); } Set<String> fewKeysSet = new HashSet<String>() { { add("key0"); add("key2"); } }; // the call to removeAll myCache.removeAll(fewKeysSet); for (int i = 0; i < 3; i++) { if (i == 0 || i == 2) { assertThat(myCache.get("key" + i), is(nullValue())); } else { assertThat(myCache.get("key" + i), is("value" + i)); } } }
Example 9
Source File: EventNotificationTest.java From ehcache3 with Apache License 2.0 | 5 votes |
@Test public void testMultiThreadedSyncNotifications() throws InterruptedException { CacheConfiguration<Number, Number> cacheConfiguration = newCacheConfigurationBuilder(Number.class, Number.class, newResourcePoolsBuilder() .heap(10L, EntryUnit.ENTRIES)) .build(); CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration) .build(true); Cache<Number, Number> cache = cacheManager.getCache("cache", Number.class, Number.class); cache.getRuntimeConfiguration() .registerCacheEventListener(listener1, EventOrdering.UNORDERED, EventFiring.SYNCHRONOUS, EnumSet .of(EventType.CREATED, EventType.EVICTED)); Thread[] operators = new Thread[10]; for (int i = 0; i < 10; i++) { operators[i] = new Thread(new CachePutOperator(cache, i), "CACHE-PUT-OPERATOR_" + i); operators[i].start(); } for (int i = 0; i < 10; i++) { operators[i].join(); } int entryCount = 0; for (Cache.Entry<Number, Number> entry : cache) { entryCount++; } cacheManager.close(); assertEquals(100, listener1.created.get()); assertEquals(100 - entryCount, listener1.evicted.get()); }
Example 10
Source File: EhcacheBulkMethodsITest.java From ehcache3 with Apache License 2.0 | 5 votes |
@Test public void testGetAll_with_cache_loader() throws Exception { CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class, heap(100)); CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class); CacheLoaderWriter cacheLoaderWriter = mock(CacheLoaderWriter.class); when(cacheLoaderWriter.load(ArgumentMatchers.any())).thenThrow(new RuntimeException("We should not have called .load() but .loadAll()")); when(cacheLoaderWriterProvider.createCacheLoaderWriter(anyString(), ArgumentMatchers.any(CacheConfiguration.class))).thenReturn(cacheLoaderWriter); CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider); CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.withLoaderWriter(cacheLoaderWriter).build(); CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true); when(cacheLoaderWriter.loadAll(argThat(IsCollectionContaining.<String>hasItem("key0")))).thenReturn(new HashMap(){{put("key0","value0");}}); when(cacheLoaderWriter.loadAll(argThat(IsCollectionContaining.<String>hasItem("key2")))).thenReturn(new HashMap(){{put("key2","value2");}}); Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class); Set<String> fewKeysSet = new HashSet<String>() { { add("key0"); add("key2"); } }; // the call to getAll Map<String, String> fewEntries = myCache.getAll(fewKeysSet); assertThat(fewEntries.size(), is(2)); assertThat(fewEntries.get("key0"), is("value0")); assertThat(fewEntries.get("key2"), is("value2")); }
Example 11
Source File: Tiering.java From ehcache3 with Apache License 2.0 | 5 votes |
@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 12
Source File: TestEhcache.java From PeonyFramwork with Apache License 2.0 | 5 votes |
public static void main(String[] args){ CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("preConfigured", CacheConfigurationBuilder.newCacheConfigurationBuilder().buildConfig(Long.class, String.class)) .build(true); Cache<Long, String> preConfigured = cacheManager.getCache("preConfigured", Long.class, String.class); Cache<Long, TestData> myCache = cacheManager.createCache("myCache", CacheConfigurationBuilder.newCacheConfigurationBuilder().buildConfig(Long.class, TestData.class)); Cache<Long, TestData2> myCache2 = cacheManager.createCache("myCache2", CacheConfigurationBuilder.newCacheConfigurationBuilder().buildConfig(Long.class, TestData2.class)); TestData data=new TestData(); myCache.put(1L, data); myCache.put(1L, data); myCache.put(1L,new TestData()); myCache.put(1L, data); myCache2.put(2l,data.testData2); data.a=30; data.testData2.a=50; TestData value = myCache.get(1L); log.info(value.toString()); cacheManager.close(); }
Example 13
Source File: OffHeapOsgiTest.java From ehcache3 with Apache License 2.0 | 5 votes |
public static void testOffHeapInOsgi() { CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("myCache", newCacheConfigurationBuilder(Long.class, String.class, newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).offheap(10, MemoryUnit.MB)) .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 14
Source File: IntegrationConfigurationTest.java From ehcache3 with Apache License 2.0 | 5 votes |
@Test public void testWriteBehind() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SAXException, IOException, InterruptedException { Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/writebehind-cache.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); assertThat(cache, notNullValue()); assertThat(cache.get(1), notNullValue()); final Number key = 42L; TestCacheLoaderWriter.latch = new CountDownLatch(1); cache.put(key, "Bye y'all!"); TestCacheLoaderWriter.latch.await(2, TimeUnit.SECONDS); assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key)); assertThat(configuration.getCacheConfigurations().containsKey("template1"), is(true)); final Cache<Number, String> templateCache = cacheManager.getCache("template1", Number.class, String.class); assertThat(templateCache, notNullValue()); assertThat(templateCache.get(1), notNullValue()); final Number key1 = 100L; TestCacheLoaderWriter.latch = new CountDownLatch(2); templateCache.put(42L, "Howdy!"); templateCache.put(key1, "Bye y'all!"); TestCacheLoaderWriter.latch.await(2, TimeUnit.SECONDS); assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key1)); }
Example 15
Source File: ThreadPools.java From ehcache3 with Apache License 2.0 | 5 votes |
@Test public void writeBehind() throws Exception { // tag::writeBehind[] CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .using(PooledExecutionServiceConfigurationBuilder.newPooledExecutionServiceConfigurationBuilder() // <1> .defaultPool("dflt", 0, 10) .pool("defaultWriteBehindPool", 1, 3) .pool("cache2Pool", 2, 2) .build()) .withDefaultWriteBehindThreadPool("defaultWriteBehindPool") // <2> .withCache("cache1", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES)) .withLoaderWriter(new SampleLoaderWriter<>(singletonMap(41L, "zero"))) .withService(WriteBehindConfigurationBuilder .newBatchedWriteBehindConfiguration(1, TimeUnit.SECONDS, 3) .queueSize(3) .concurrencyLevel(1))) .withCache("cache2", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES)) .withLoaderWriter(new SampleLoaderWriter<>(singletonMap(41L, "zero"))) .withService(WriteBehindConfigurationBuilder .newBatchedWriteBehindConfiguration(1, TimeUnit.SECONDS, 3) .useThreadPool("cache2Pool") // <3> .queueSize(3) .concurrencyLevel(2))) .build(true); Cache<Long, String> cache1 = cacheManager.getCache("cache1", Long.class, String.class); Cache<Long, String> cache2 = cacheManager.getCache("cache2", Long.class, String.class); cacheManager.close(); // end::writeBehind[] }
Example 16
Source File: SimpleOsgiTest.java From ehcache3 with Apache License 2.0 | 5 votes |
public static void testEhcache3AsBundle() { CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("myCache", newCacheConfigurationBuilder(Long.class, String.class, heap(10)) .build()) .build(true); Cache<Long, String> myCache = cacheManager.getCache("myCache", Long.class, String.class); myCache.put(42L, "DaAnswer!"); assertEquals("DaAnswer!", myCache.get(42L)); }
Example 17
Source File: SimpleClusteredCacheByXmlTest.java From ehcache3 with Apache License 2.0 | 5 votes |
@Test public void testViaXml() throws Exception { final Configuration configuration = new XmlConfiguration(this.getClass().getResource(SIMPLE_CLUSTER_XML)); final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration); assertThat(cacheManager, is(instanceOf(PersistentCacheManager.class))); cacheManager.init(); final Cache<Long, String> cache = cacheManager.getCache("simple-cache", Long.class, String.class); assertThat(cache, is(not(nullValue()))); cacheManager.close(); }
Example 18
Source File: XAGettingStarted.java From ehcache3 with Apache License 2.0 | 5 votes |
@Test @SuppressWarnings("unchecked") public void testXACacheWithWriteThrough() throws Exception { // tag::testXACacheWithWriteThrough[] BitronixTransactionManager transactionManager = TransactionManagerServices.getTransactionManager(); // <1> Class<CacheLoaderWriter<?, ?>> klazz = (Class<CacheLoaderWriter<?, ?>>) (Class) (SampleLoaderWriter.class); 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> .withService(new DefaultCacheLoaderWriterConfiguration(klazz, singletonMap(1L, "eins"))) // <6> .build() ) .build(true); Cache<Long, String> xaCache = cacheManager.getCache("xaCache", Long.class, String.class); transactionManager.begin(); // <7> { assertThat(xaCache.get(1L), equalTo("eins")); // <8> xaCache.put(1L, "one"); // <9> } transactionManager.commit(); // <10> cacheManager.close(); transactionManager.shutdown(); // end::testXACacheWithWriteThrough[] }
Example 19
Source File: ManagementTest.java From ehcache3 with Apache License 2.0 | 4 votes |
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[] }
Example 20
Source File: EventNotificationTest.java From ehcache3 with Apache License 2.0 | 4 votes |
@Test public void testMultiThreadedSyncAsyncNotifications() throws InterruptedException { AsynchronousListener asyncListener = new AsynchronousListener(); asyncListener.resetLatchCount(100); CacheConfiguration<Number, Number> cacheConfiguration = newCacheConfigurationBuilder(Number.class, Number.class, newResourcePoolsBuilder().heap(10L, EntryUnit.ENTRIES)) .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(1))) .build(); CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration) .using(new TimeSourceConfiguration(testTimeSource)) .build(true); testTimeSource.setTimeMillis(0); Cache<Number, Number> cache = cacheManager.getCache("cache", Number.class, Number.class); cache.getRuntimeConfiguration().registerCacheEventListener(asyncListener, EventOrdering.UNORDERED, EventFiring.ASYNCHRONOUS, EnumSet .of(EventType.CREATED, EventType.EXPIRED)); cache.getRuntimeConfiguration().registerCacheEventListener(listener1, EventOrdering.ORDERED, EventFiring.SYNCHRONOUS, EnumSet .of(EventType.CREATED, EventType.EXPIRED)); Thread[] operators = new Thread[10]; for (int i = 0; i < 10; i++) { operators[i] = new Thread(new CachePutOperator(cache, i), "CACHE-PUT-OPERATOR_" + i); operators[i].start(); } for (int i = 0; i < 10; i++) { operators[i].join(); } int entryCount = 0; for (Cache.Entry<Number, Number> entry : cache) { entryCount++; } testTimeSource.setTimeMillis(2000); operators = new Thread[10]; for (int i = 0; i < 10; i++) { operators[i] = new Thread(new CacheGetOperator(cache, i), "CACHE-GET-OPERATOR_" + i); operators[i].start(); } for (int i = 0; i < 10; i++) { operators[i].join(); } cacheManager.close(); assertEquals(100, listener1.created.get()); assertEquals(entryCount, listener1.expired.get()); assertEquals(100, asyncListener.created.get()); assertEquals(entryCount, asyncListener.expired.get()); }