org.cache2k.Cache Java Examples
The following examples show how to use
org.cache2k.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: Cache2kBuilderTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void duplicateCacheName() { String _managerName = getClass().getName() + ".duplicateCacheName"; Log.registerSuppression(CacheManager.class.getName() + ":" + _managerName, new Log.SuppressionCounter()); CacheManager mgr = CacheManager.getInstance(_managerName); try { Cache c0 = Cache2kBuilder.forUnknownTypes() .manager(mgr) .eternal(true) .name(this.getClass(), "same") .build(); Cache c1 = Cache2kBuilder.forUnknownTypes() .manager(mgr) .eternal(true) .name(this.getClass(), "same") .build(); fail("exception expected"); } catch (IllegalStateException ex) { } mgr.close(); }
Example #2
Source File: CacheLoaderTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void testFunctionalLoader() { Cache<Integer,Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() { @Override public void extend(final Cache2kBuilder<Integer, Integer> b) { b.loader(new FunctionalCacheLoader<Integer, Integer>() { @Override public Integer load(final Integer key) throws Exception { return key * 7; } }); } }); int v = c.get(1); assertEquals(7, v); }
Example #3
Source File: CacheLoaderTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void testLoadNull() { Cache<Integer,Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() { @Override public void extend(final Cache2kBuilder<Integer, Integer> b) { b .loader(new CacheLoader<Integer, Integer>() { @Override public Integer load(final Integer key) throws Exception { return null; } }) .permitNullValues(true); } }); assertNull(c.get(5)); assertTrue(c.containsKey(5)); }
Example #4
Source File: DateFormattingBenchmark.java From cache2k-benchmark with Apache License 2.0 | 6 votes |
/** * Always produce a new date formatter. */ @Test public void testWithCacheNewFormatter() { final PrintWriter w = new PrintWriter(new CharArrayWriter()); Cache<Date, String> c = Cache2kBuilder.of(Date.class, String.class) .loader(new CacheLoader<Date, String>() { @Override public String load(Date o) { DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE); return df.format(o); } }) .build(); List<Date> l = provideListWith3MillionDates(); for (Date d : l) { w.print(c.get(d)); } c.close(); }
Example #5
Source File: CacheRule.java From cache2k with Apache License 2.0 | 6 votes |
Cache<K, V> buildCache() { String _name = description.getTestClass().getName(); Cache2kBuilder b = getInitialBuilder(); for (Specialization sp : configurationSpecialization) { sp.extend(b); } if (shared) { b.name(description.getTestClass()); sharedCache.put(_name, _name); } else { if (sharedCache.containsKey(_name)) { throw new IllegalArgumentException("Shared cache usage: Method rule must be identical instance."); } b.name(description.getTestClass(), description.getMethodName()); } return b.build(); }
Example #6
Source File: WeigherTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void weightUpdatedWithLoader() { long _size = 2; Cache<Integer, Integer> c = builder(Integer.class, Integer.class) .eternal(true) .entryCapacity(-1) .weigher(new Weigher<Integer, Integer>() { @Override public long weigh(final Integer key, final Integer value) { return value; } }) .maximumWeight(_size) .loader(new PatternLoader(1, 1, 100, 1)) .strictEviction(true) .build(); c.get(1); c.get(2); assertEquals(2, countEntriesViaIteration()); reload(2); // 100 assertEquals(1, countEntriesViaIteration()); assertTrue("the entry that is updated is never removed", c.containsKey(2)); reload(1); assertEquals(1, countEntriesViaIteration()); assertFalse("the other entry is removed", c.containsKey(2)); }
Example #7
Source File: ListenerTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void customExecutor() { final AtomicInteger _counter = new AtomicInteger(); Cache<Integer, Integer> c = Cache2kBuilder.of(Integer.class, Integer.class) .addAsyncListener(new CacheEntryCreatedListener<Integer, Integer>() { @Override public void onEntryCreated(final Cache<Integer, Integer> cache, final CacheEntry<Integer, Integer> entry) { } }) .asyncListenerExecutor(new Executor() { @Override public void execute(final Runnable command) { _counter.incrementAndGet(); } }) .build(); c.put(1,2); c.close(); assertEquals(1, _counter.get()); }
Example #8
Source File: SlowExpiryTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void testExpireNoKeepSharpExpiryBeyondSafetyGap() { HeapCache.Tunable t = TunableFactory.get(HeapCache.Tunable.class); final Cache<Integer, Integer> c = cache = builder(Integer.class, Integer.class) .loader(new IntCountingCacheSource()) .expireAfterWrite(t.sharpExpirySafetyGapMillis + 3, TimeUnit.MILLISECONDS) .keepDataAfterExpired(false) .sharpExpiry(true) .build(); c.getAll(toIterable(1, 2, 3)); await(new Condition() { @Override public boolean check() throws Exception { return getInfo().getTimerEventCount() >= 3; } }); }
Example #9
Source File: CacheManagerAndCacheLifeCycleTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void differentClassLoaderDifferentManager() { CacheManager.getInstance(); ClassLoader cl1 = new URLClassLoader(new URL[0], this.getClass().getClassLoader()); ClassLoader cl2 = new URLClassLoader(new URL[0], this.getClass().getClassLoader()); CacheManager cm1 = CacheManager.getInstance(cl1); CacheManager cm2 = CacheManager.getInstance(cl2); assertNotSame(cm1, cm2); assertFalse(cm1.isClosed()); assertFalse(cm2.isClosed()); Cache c1 = Cache2kBuilder.forUnknownTypes().manager(cm1).build(); Cache c2 = Cache2kBuilder.forUnknownTypes().manager(cm2).build(); CacheManager.closeAll(cl1); CacheManager.closeAll(cl2); assertTrue(cm1.isClosed()); assertTrue(cm2.isClosed()); assertTrue(c1.isClosed()); assertTrue(c2.isClosed()); }
Example #10
Source File: SlowExpiryTest.java From cache2k with Apache License 2.0 | 6 votes |
/** * Refresh an entry immediately. */ @Test public void manualExpire_nowIsh_getLater_doesRefresh() throws Exception { final Cache<Integer, Integer> c = builder(Integer.class, Integer.class) .expireAfterWrite(5, TimeUnit.MINUTES) .refreshAhead(true) .loader(new CacheLoader<Integer, Integer>() { @Override public Integer load(final Integer key) throws Exception { return 4711; } }) .build(); c.put(1,2); c.expireAt(1, millis() + TestingParameters.MINIMAL_TICK_MILLIS); sleep(TestingParameters.MINIMAL_TICK_MILLIS * 21); await(new Condition() { @Override public boolean check() throws Exception { return c.get(1) == 4711; } }); }
Example #11
Source File: TimingHandlerTest.java From cache2k with Apache License 2.0 | 6 votes |
/** * Check that the maximize concurrency is routed through to the timing handler properly. */ @Test public void maximizeConcurrency() { Cache<Integer, Integer> c = Cache2kBuilder.of(Integer.class, Integer.class) .boostConcurrency(true) .expireAfterWrite(5, TimeUnit.MINUTES) .loader(new CacheLoader<Integer, Integer>() { @Override public Integer load(final Integer key) throws Exception { return key + 123; } }) .build(); int _timerMask = ((TimingHandler.Static) c.requestInterface(HeapCache.class).timing).timerMask; if (Runtime.getRuntime().availableProcessors() >1) { assertTrue(_timerMask > 0); } c.close(); }
Example #12
Source File: ExpiryTest.java From cache2k with Apache License 2.0 | 5 votes |
/** * Switching to eternal means exceptions expire immediately. */ @Test public void testEternal_noKeep() throws Exception { IntCountingCacheSource g = new IntCountingCacheSource() { @Override public Integer load(final Integer o) { incrementLoadCalledCount(); if (o == 99) { throw new RuntimeException("ouch"); } return o; } }; final Cache<Integer, Integer> c = cache = builder(Integer.class, Integer.class) .loader(g) .eternal(true) .build(); assertEquals("no miss", 0, g.getLoaderCalledCount()); c.get(1802); assertEquals("one miss", 1, g.getLoaderCalledCount()); c.get(1802); assertEquals("one miss", 1, g.getLoaderCalledCount()); assertTrue(((InternalCache) c).getEntryState(1802).contains("nextRefreshTime=ETERNAL")); try { Integer obj = c.get(99); fail("exception expected"); } catch (CacheLoaderException ex) { assertTrue("no expiry on exception", !ex.toString().contains(EXPIRY_MARKER)); assertTrue(ex.getCause() instanceof RuntimeException); } assertEquals("miss", 2, g.getLoaderCalledCount()); CacheEntry<Integer, Integer> e = c.getEntry(99); entryHasException(e); assertEquals(RuntimeException.class, e.getException().getClass()); assertEquals("miss", 3, g.getLoaderCalledCount()); }
Example #13
Source File: ClockProEvictionWithWeigherTest.java From cache2k with Apache License 2.0 | 5 votes |
protected Cache<Integer, Integer> provideCache(long _size) { return builder(Integer.class, Integer.class) .eternal(true) .entryCapacity(-1) // reset capacity, capacity is already set via builder() .weigher(new Weigher<Integer, Integer>() { @Override public long weigh(final Integer key, final Integer value) { return 1; } }) .maximumWeight(_size) .strictEviction(true) .build(); }
Example #14
Source File: SlowExpiryTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void testSuppressExceptionImmediateExpiry() throws Exception { BasicCacheTest.OccasionalExceptionSource src = new BasicCacheTest.OccasionalExceptionSource(); final Cache<Integer, Integer> c = builder(Integer.class, Integer.class) .expireAfterWrite(0, TimeUnit.MINUTES) .retryInterval(TestingParameters.MINIMAL_TICK_MILLIS, TimeUnit.MILLISECONDS) .resilienceDuration(Long.MAX_VALUE, TimeUnit.MILLISECONDS) .keepDataAfterExpired(true) .loader(src) .build(); c.get(2); c.get(2); assertEquals(1, getInfo().getSuppressedExceptionCount()); }
Example #15
Source File: CacheLoaderTest.java From cache2k with Apache License 2.0 | 5 votes |
protected Cache<Integer, Integer> cacheWithLoader() { return target.cache(new CacheRule.Specialization<Integer, Integer>() { @Override public void extend(final Cache2kBuilder<Integer, Integer> b) { b .loader(new CacheLoader<Integer, Integer>() { @Override public Integer load(final Integer key) throws Exception { loaderExecutionCount++; return key * 2; } }); } }); }
Example #16
Source File: JCacheAdapter.java From cache2k with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Override public <T> T unwrap(Class<T> clazz) { if (Cache.class.equals(clazz)) { return (T) cache; } throw new IllegalArgumentException("requested class unknown"); }
Example #17
Source File: CacheLoaderTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void testAsyncLoaderWithExecutorWithAsync() { final AtomicInteger loaderCalled = new AtomicInteger(); final AtomicInteger loaderExecuted = new AtomicInteger(); Cache<Integer,Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() { @Override public void extend(final Cache2kBuilder<Integer, Integer> b) { b.loader(new AsyncCacheLoader<Integer, Integer>() { @Override public void load(final Integer key, final Context<Integer, Integer> ctx, final Callback<Integer> callback) { loaderCalled.incrementAndGet(); ctx.getLoaderExecutor().execute(new Runnable() { @Override public void run() { loaderExecuted.incrementAndGet(); callback.onLoadSuccess(key); } }); } }); } }); CompletionWaiter w = new CompletionWaiter(); c.loadAll(TestingBase.keys(1, 2, 1802), w); w.awaitCompletion(); assertEquals(1, (int) c.peek(1)); Object o1 = c.peek(1802); assertTrue(c.peek(1802) == o1); w = new CompletionWaiter(); c.reloadAll(TestingBase.keys(1802, 4, 5), w); w.awaitCompletion(); assertNotNull(c.peek(1802)); assertTrue(c.peek(1802) != o1); }
Example #18
Source File: BasicCacheTest.java From cache2k with Apache License 2.0 | 5 votes |
long getRefreshedTimeViaEntryProcessor(Cache<Integer, Integer> c, int key) { return c.invoke(key, new EntryProcessor<Integer, Integer, Long>() { @Override public Long process(final MutableCacheEntry<Integer, Integer> e) throws Exception { return e.getRefreshedTime(); } }); }
Example #19
Source File: ExpiryTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void testFetchAlwaysWithVariableExpiryInPastAfterLoad() { IntCountingCacheSource g = new IntCountingCacheSource(); final Cache<Integer, Integer> c = cache = Cache2kBuilder.of(Integer.class, Integer.class) .loader(g) .expiryPolicy(new ExpiryPolicy<Integer, Integer>() { @Override public long calculateExpiryTime(final Integer key, final Integer value, final long loadTime, final CacheEntry<Integer, Integer> oldEntry) { sleep(3); return loadTime + 1; } }) .expireAfterWrite(0, TimeUnit.SECONDS).build(); checkAlwaysLoaded(g, c); }
Example #20
Source File: IntegrationTest.java From cache2k with Apache License 2.0 | 5 votes |
/** * The name of the default manager is set by the configuration. * Not working, will be moved. */ public void defaultManagerName() { Cache c = Cache2kBuilder.forUnknownTypes().name("flowers").build(); assertTrue("default manager", c.getCacheManager().isDefaultManager()); assertEquals("myApp", c.getCacheManager().getName()); c.close(); }
Example #21
Source File: CacheManagerAndCacheLifeCycleTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void testToStringAnon() { Cache<Integer, Integer> c = Cache2kBuilder.of(Integer.class, Integer.class) .eternal(true) .build(); c.toString(); c.close(); }
Example #22
Source File: XmlConfigurationTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void cache2kSemanticsIfEmptyConfigurationPresent() throws Exception { CachingProvider p = Caching.getCachingProvider(); javax.cache.CacheManager cm = p.getCacheManager(new URI("empty"), null); javax.cache.Cache<String, BigDecimal> c = cm.createCache("test2", new MutableConfiguration<String, BigDecimal>()); assertTrue(c instanceof JCacheAdapter); }
Example #23
Source File: InternalCache2kBuilder.java From cache2k with Apache License 2.0 | 5 votes |
@Override public void onEntryEvicted(final Cache<K, V> c, final CacheEntry<K, V> e) { dispatcher.queue(new AsyncEvent<K>() { @Override public K getKey() { return e.getKey(); } @Override public void execute() { listener.onEntryEvicted(c, e); } }); }
Example #24
Source File: JmxSupportTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void testCacheCreated() throws Exception { String _name = getClass().getName() + ".testCacheCreated"; Cache c = Cache2kBuilder.of(Object.class, Object.class) .name(_name) .eternal(true) .enableJmx(true) .build(); MBeanInfo i = getCacheInfo(_name); assertEquals(CacheMXBeanImpl.class.getName(), i.getClassName()); c.close(); }
Example #25
Source File: CacheLoaderTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void prefetch_present_listener() { final Cache<Integer,Integer> c = cacheWithLoader(); CompletionWaiter w = new CompletionWaiter(); c.put(1, 1); c.prefetchAll(toIterable(1), w); w.awaitCompletion(); assertTrue(c.containsKey(1)); assertTrue(latestInfo(c).getAsyncLoadsStarted() == 0); }
Example #26
Source File: Cache2kBuilderTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void typesParametersWithList() { Cache<Long, List> c = Cache2kBuilder.forUnknownTypes() .valueType(List.class) .keyType(Long.class) .eternal(true) .build(); c.close(); }
Example #27
Source File: CacheTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void testContains() { Cache<String,String> c = Cache2kBuilder.of(String.class, String.class) .eternal(true) .build(); String val = c.peek("something"); assertNull(val); c.put("something", "hello"); assertTrue(c.containsKey("something")); assertFalse(c.containsKey("dsaf")); c.close(); }
Example #28
Source File: CacheTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void testGetEntry() { Cache<String,String> c = Cache2kBuilder.of(String.class, String.class) .eternal(true) .build(); String val = c.peek("something"); assertNull(val); c.put("something", "hello"); CacheEntry<String, String> e = c.getEntry("something"); assertNotNull(e); assertEquals("hello", e.getValue()); c.close(); }
Example #29
Source File: ExpiryTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void testEternalExceptionsEternal() { IntCountingCacheSource g = new IntCountingCacheSource() { @Override public Integer load(final Integer o) { incrementLoadCalledCount(); if (o == 99) { throw new RuntimeException("ouch"); } return o; } }; final Cache<Integer, Integer> c = cache = builder(Integer.class, Integer.class) .loader(g) .eternal(true) .retryInterval(Long.MAX_VALUE, TimeUnit.MILLISECONDS) .build(); assertEquals("no miss", 0, g.getLoaderCalledCount()); c.get(1802); assertEquals("one miss", 1, g.getLoaderCalledCount()); c.get(1802); assertEquals("one miss", 1, g.getLoaderCalledCount()); assertTrue(((InternalCache) c).getEntryState(1802).contains("nextRefreshTime=ETERNAL")); CacheEntry<Integer,Integer> e = c.getEntry(99); entryHasException(e); assertEquals(RuntimeException.class, e.getException().getClass()); assertEquals("two miss", 2, g.getLoaderCalledCount()); assertTrue(((InternalCache) c).getEntryState(99).contains("nextRefreshTime=ETERNAL")); e = c.getEntry(99); entryHasException(e); assertEquals(RuntimeException.class, e.getException().getClass()); assertEquals("two miss", 2, g.getLoaderCalledCount()); try { c.get(99); fail("expect exception"); } catch (Exception ex) { assertThat(ex.toString(), containsString("expiry=ETERNAL")); } }
Example #30
Source File: ListenerTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void asyncUpdateListenerException() { String _logName = getClass().getName() + ".asyncUpdateListenerException"; final Log.SuppressionCounter _suppressionCounter = new Log.SuppressionCounter(); Log.registerSuppression("org.cache2k.Cache/default:" + _logName, _suppressionCounter); Cache<Integer, Integer> c = Cache2kBuilder.of(Integer.class, Integer.class) .name(_logName) .eternal(true) .addAsyncListener(new CacheEntryUpdatedListener<Integer, Integer>() { @Override public void onEntryUpdated( final Cache<Integer, Integer> cache, final CacheEntry<Integer, Integer> currentEntry, final CacheEntry<Integer, Integer> entryWithNewData) { throw new RuntimeException("ouch"); } }) .build(); c.put(1, 2); c.put(1, 2); ConcurrencyHelper.await(new Condition() { @Override public boolean check() throws Exception { return _suppressionCounter.getWarnCount() == 1; } }); c.close(); }