method2testcases
stringlengths 118
6.63k
|
---|
### Question:
ConcurrencyUtil { public static int selectLock(final Object key, int numberOfLocks) throws CacheException { int number = numberOfLocks & (numberOfLocks - 1); if (number != 0) { throw new CacheException("Lock number must be a power of two: " + numberOfLocks); } if (key == null) { return 0; } else { int hash = hash(key) & (numberOfLocks - 1); return hash; } } private ConcurrencyUtil(); static int hash(Object object); static int selectLock(final Object key, int numberOfLocks); static void shutdownAndWaitForTermination(ExecutorService pool, int waitSeconds); }### Answer:
@Test public void testStripingDistribution() { int[] lockIndexes = new int[2048]; for (int i = 0; i < 20480 * 3; i++) { String key = "" + i * 3 / 2 + i; key += key.hashCode(); int lock = ConcurrencyUtil.selectLock(key, 2048); lockIndexes[lock]++; } int outliers = 0; for (int i = 0; i < 2048; i++) { if (20 <= lockIndexes[i] && lockIndexes[i] <= 40) { continue; } LOG.info(i + ": " + lockIndexes[i]); outliers++; } assertTrue(outliers <= 128); }
@Test public void testNullKey() { ConcurrencyUtil.selectLock(null, 2048); ConcurrencyUtil.selectLock("", 2048); }
@Test public void testEvenLockNumber() { try { ConcurrencyUtil.selectLock("anything", 100); } catch (CacheException e) { } } |
### Question:
BlockingCache implements Ehcache { protected Ehcache getCache() { return cache; } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); @Override Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); LiveCacheStatistics getLiveCacheStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); CacheWriterManager getWriterManager(); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); void putWithWriter(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); boolean removeWithWriter(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); int getSizeBasedOnAccuracy(int statisticsAccuracy); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); void registerCacheWriter(CacheWriter cacheWriter); void unregisterCacheWriter(); CacheWriter getRegisteredCacheWriter(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); void registerCacheUsageListener(CacheUsageListener cacheUsageListener); void removeCacheUsageListener(CacheUsageListener cacheUsageListener); boolean isStatisticsEnabled(); void setStatisticsEnabled(boolean enabledStatistics); SampledCacheStatistics getSampledCacheStatistics(); void setSampledStatisticsEnabled(boolean enabledStatistics); boolean isSampledStatisticsEnabled(); Object getInternalContext(); void disableDynamicFeatures(); boolean isCoherent(); void setCoherent(boolean coherent); void waitUntilCoherent(); void setTransactionManagerLookup(TransactionManagerLookup transactionManagerLookup); }### Answer:
@Test public void testThrashBlockingCache() throws Exception { Ehcache cache = manager.getCache("sampleCache1"); blockingCache = new BlockingCache(cache); long duration = thrashCache(blockingCache, 50, 500L, 1000L); LOG.debug("Thrash Duration:" + duration); } |
### Question:
BlockingCache implements Ehcache { public Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument) throws CacheException { throw new CacheException("This method is not appropriate for a Blocking Cache"); } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); @Override Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); LiveCacheStatistics getLiveCacheStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); CacheWriterManager getWriterManager(); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); void putWithWriter(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); boolean removeWithWriter(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); int getSizeBasedOnAccuracy(int statisticsAccuracy); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); void registerCacheWriter(CacheWriter cacheWriter); void unregisterCacheWriter(); CacheWriter getRegisteredCacheWriter(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); void registerCacheUsageListener(CacheUsageListener cacheUsageListener); void removeCacheUsageListener(CacheUsageListener cacheUsageListener); boolean isStatisticsEnabled(); void setStatisticsEnabled(boolean enabledStatistics); SampledCacheStatistics getSampledCacheStatistics(); void setSampledStatisticsEnabled(boolean enabledStatistics); boolean isSampledStatisticsEnabled(); Object getInternalContext(); void disableDynamicFeatures(); boolean isCoherent(); void setCoherent(boolean coherent); void waitUntilCoherent(); void setTransactionManagerLookup(TransactionManagerLookup transactionManagerLookup); }### Answer:
@Test public void testGetWithLoader() { super.testGetWithLoader(); } |
### Question:
ExplicitLockingCache implements Ehcache { public boolean putIfAbsent(Element element) { try { acquireWriteLockOnKey(element.getKey()); if (!isKeyInCache(element.getKey())) { this.put(element); return true; } return false; } finally { releaseWriteLockOnKey(element.getKey()); } } ExplicitLockingCache(Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); @Override Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); LiveCacheStatistics getLiveCacheStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); int getSizeBasedOnAccuracy(int statisticsAccuracy); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); void registerCacheUsageListener(CacheUsageListener cacheUsageListener); void removeCacheUsageListener(CacheUsageListener cacheUsageListener); boolean isStatisticsEnabled(); void setStatisticsEnabled(boolean enabledStatistics); SampledCacheStatistics getSampledCacheStatistics(); void setSampledStatisticsEnabled(boolean enabledStatistics); boolean isSampledStatisticsEnabled(); Object getInternalContext(); void acquireReadLockOnKey(Object key); void acquireWriteLockOnKey(Object key); void releaseReadLockOnKey(Object key); void releaseWriteLockOnKey(Object key); boolean tryReadLockOnKey(Object key, long timeout); boolean tryWriteLockOnKey(Object key, long timeout); boolean putIfAbsent(Element element); void disableDynamicFeatures(); void putWithWriter(Element element); boolean removeWithWriter(Object key); void registerCacheWriter(CacheWriter cacheWriter); void unregisterCacheWriter(); CacheWriter getRegisteredCacheWriter(); CacheWriterManager getWriterManager(); }### Answer:
@Test public void testPutIfAbsent() { assertEquals(testCache.get("putIfAbsent"), null); testCache.putIfAbsent(new Element("putIfAbsent", "1")); assertEquals(testCache.get("putIfAbsent").getValue(), "1"); testCache.putIfAbsent(new Element("putIfAbsent", "2")); assertEquals(testCache.get("putIfAbsent").getValue(), "1"); } |
### Question:
SizeOfEngineLoader implements SizeOfEngineFactory { @Override public SizeOfEngine createSizeOfEngine(final int maxObjectCount, final boolean abort, final boolean silent) { SizeOfEngineFactory currentFactory = this.factory; if (currentFactory != null) { return currentFactory.createSizeOfEngine(maxObjectCount, abort, silent); } return new DefaultSizeOfEngine(maxObjectCount, abort, silent); } SizeOfEngineLoader(ClassLoader classLoader); private SizeOfEngineLoader(); static SizeOfEngine newSizeOfEngine(final int maxObjectCount, final boolean abort, final boolean silent); @Override SizeOfEngine createSizeOfEngine(final int maxObjectCount, final boolean abort, final boolean silent); void reload(); synchronized boolean load(Class<? extends SizeOfEngineFactory> clazz, boolean reload); static final SizeOfEngineLoader INSTANCE; }### Answer:
@Test public void testFallsBackToDefaultSizeOfEngine() { final SizeOfEngine sizeOfEngine = SizeOfEngineLoader.INSTANCE.createSizeOfEngine(10, true, true); assertThat(sizeOfEngine, notNullValue()); assertThat(sizeOfEngine, instanceOf(DefaultSizeOfEngine.class)); }
@Test public void testUsesServiceLoaderWhenItCan() { ClassLoader cl = new CheatingClassLoader(); SizeOfEngineLoader loader = new SizeOfEngineLoader(cl); assertThat(loader.createSizeOfEngine(10, true, true), sameInstance(constantSizeOfEngine)); } |
### Question:
AnnotationProxyFactory { public static <T extends Annotation> T getAnnotationProxy(Annotation customAnnotation, Class<T> referenceAnnotation) { InvocationHandler handler = new AnnotationInvocationHandler(customAnnotation); return (T) Proxy.newProxyInstance(referenceAnnotation.getClassLoader(), new Class[] {referenceAnnotation}, handler); } private AnnotationProxyFactory(); static T getAnnotationProxy(Annotation customAnnotation, Class<T> referenceAnnotation); }### Answer:
@Test(expected=UnsupportedOperationException.class) public void NoDefaultValueInReferenceAnnotationAndNoImplementationInCustomThrowsException_Test() { CustomAnnotation customAnnotation = UsingCustomAnnotation.class.getAnnotation(CustomAnnotation.class); ReferenceAnnotation annotationProxy = AnnotationProxyFactory.getAnnotationProxy(customAnnotation, ReferenceAnnotation.class); annotationProxy.things(); }
@Test public void NoImplementationInCustomFallsBackToReferenceImplementation_Test() { CustomAnnotation customAnnotation = UsingCustomAnnotation.class.getAnnotation(CustomAnnotation.class); ReferenceAnnotation annotationProxy = AnnotationProxyFactory.getAnnotationProxy(customAnnotation, ReferenceAnnotation.class); assertEquals("hello",annotationProxy.version()); }
@Test public void IfMethodExistsInCustomAnnotationRedirectsToIt_Test() { CustomAnnotation customAnnotation = UsingCustomAnnotation.class.getAnnotation(CustomAnnotation.class); ReferenceAnnotation annotationProxy = AnnotationProxyFactory.getAnnotationProxy(customAnnotation, ReferenceAnnotation.class); assertEquals(true,annotationProxy.deprecated()); }
@Test public void IfMethodExistsInCustomAnnotationButReturnTypeIsDifferentFallsBackToReferenceImplementation_Test() { CustomAnnotation customAnnotation = UsingCustomAnnotation.class.getAnnotation(CustomAnnotation.class); ReferenceAnnotation annotationProxy = AnnotationProxyFactory.getAnnotationProxy(customAnnotation, ReferenceAnnotation.class); assertEquals(5,annotationProxy.differentReturnType()); }
@Test public void DifferentReturnTypesFromDifferentMethods_Test() { CustomAnnotation customAnnotation = UsingCustomAnnotation.class.getAnnotation(CustomAnnotation.class); ReferenceAnnotation annotationProxy = AnnotationProxyFactory.getAnnotationProxy(customAnnotation, ReferenceAnnotation.class); assertEquals(Integer.class,annotationProxy.aClass()); assertEquals(ExampleEnum.TWO ,annotationProxy.anEnum()); assertEquals(customAnnotation.anAnnotation(),annotationProxy.anAnnotation()); } |
### Question:
ResourceClassLoader extends ClassLoader { @Override public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.startsWith("java.")) { return getParent().loadClass(name); } Class c = findLoadedClass(name); if (c == null) { try { c = findClass(name); } catch (ClassNotFoundException e) { c = super.loadClass(name, resolve); } } if (resolve) { resolveClass(c); } return c; } ResourceClassLoader(String prefix, ClassLoader parent); @Override synchronized Class<?> loadClass(String name, boolean resolve); @Override URL getResource(String name); }### Answer:
@Test(expected = ClassNotFoundException.class) public void contentOfTheJarNotVisibleWithNormalClassLoaderTest() throws ClassNotFoundException { Class<?> simpleClass = testCaseClassLoader.loadClass("pof.Simple"); }
@Test public void workingWithClassFromPrivateClassPathTest() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException { ResourceClassLoader resourceClassLoader = new ResourceClassLoader("private-classpath", testCaseClassLoader); Class<?> simpleClass = resourceClassLoader.loadClass("pof.Simple"); Constructor<?> simpleClassConstructor = simpleClass.getConstructor(new Class[] {}); Object simpleObject = simpleClassConstructor.newInstance(new Object[] {}); Method sayHelloMethod = simpleClass.getMethod("sayHello", new Class[] {}); Object sayHello = sayHelloMethod.invoke(simpleObject, new Object[] {}); Assert.assertEquals("hello!", sayHello); Method printVersionMethod = simpleClass.getMethod("printVersion", new Class[] {}); Object printVersion = printVersionMethod.invoke(simpleObject, new Object[] {}); Assert.assertEquals("2.6.0-SNAPSHOT", printVersion); Method getMessageInTextFileMethod = simpleClass.getMethod("getMessageInTextFile", new Class[] {}); Object message = getMessageInTextFileMethod.invoke(simpleObject, new Object[] {}); Assert.assertEquals("Congratulations ! You could read a file from a hidden resource location !", message); } |
### Question:
CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); Ehcache ehcache = ehcaches.get(name); return ehcache instanceof Cache ? (Cache) ehcache : null; } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); DiskStorePathManager getDiskStorePathManager(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); FeaturesManager getFeaturesManager(); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testGetCache() throws CacheException { CacheManager manager = new CacheManager(new Configuration().cache(new CacheConfiguration("foo", 100))); try { assertNotNull(manager.getCache("foo")); } finally { manager.shutdown(); } } |
### Question:
XATransactionalStore extends AbstractStore { public Element removeElement(Element element, ElementValueComparator comparator) throws NullPointerException { TransactionContext context = getOrCreateTransactionContext(); Element previous = getCurrentElement(element.getKey(), context); if (previous != null && previous.getValue().equals(element.getValue())) { context.addCommand(new StoreRemoveElementCommand(element, comparator), element); return previous; } return null; } XATransactionalStore(Ehcache cache, EhcacheXAStore ehcacheXAStore,
TransactionManagerLookup transactionManagerLookup, Object txnManager); boolean put(final Element element); boolean putWithWriter(final Element element, final CacheWriterManager writerManager); Element get(final Object key); Element getQuiet(final Object key); final List getKeys(); Element remove(final Object key); Element removeWithWriter(final Object key, final CacheWriterManager writerManager); void removeAll(); void dispose(); int getSize(); int getOnDiskSize(); int getOffHeapSize(); int getInMemorySize(); int getTerracottaClusteredSize(); long getInMemorySizeInBytes(); long getOffHeapSizeInBytes(); long getOnDiskSizeInBytes(); Status getStatus(); boolean containsKey(final Object key); boolean containsKeyInMemory(final Object key); boolean containsKeyOffHeap(final Object key); boolean containsKeyOnDisk(final Object key); void expireElements(); void flush(); boolean bufferFull(); Policy getInMemoryEvictionPolicy(); void setInMemoryEvictionPolicy(final Policy policy); Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); Element putIfAbsent(Element element); Element removeElement(Element element, ElementValueComparator comparator); boolean replace(Element old, Element element, ElementValueComparator comparator); Element replace(Element element); EhcacheXAResource getOrCreateXAResource(); Object getMBean(); }### Answer:
@Test public void testRemoveElement() throws Exception { transactionManager.begin(); assertEquals("Cache should be empty to start", 0, cache.getSize()); assertEquals("Cach1 should be empty to start", 0, cach1.getSize()); assertFalse(cache.removeElement(new Element("blah", "someValue"))); cache.put(new Element("blah", "value")); assertFalse(cache.removeElement(new Element("blah", "someValue"))); transactionManager.commit(); transactionManager.begin(); assertNotNull(cache.get("blah")); assertTrue(cache.removeElement(new Element("blah", "value"))); transactionManager.commit(); transactionManager.begin(); assertNull(cache.get("blah")); transactionManager.commit(); transactionManager.begin(); cache.put(new Element("key", "value")); transactionManager.commit(); transactionManager.begin(); cach1.put(new Element("random", "things")); cache.removeElement(new Element("key", "value")); Transaction tx1 = transactionManager.suspend(); transactionManager.begin(); assertTrue(cache.removeElement(new Element("key", "value"))); transactionManager.commit(); transactionManager.resume(tx1); try { transactionManager.commit(); fail("Transaction should have failed, element is deleted already"); } catch (RollbackException e) { } transactionManager.begin(); assertNull(cache.get("key")); transactionManager.commit(); transactionManager.begin(); cache.put(new Element("key", "value")); transactionManager.commit(); transactionManager.begin(); cach1.put(new Element("random", "things")); cache.removeElement(new Element("key", "value")); tx1 = transactionManager.suspend(); transactionManager.begin(); cache.put(new Element("key", "newValue")); transactionManager.commit(); transactionManager.resume(tx1); try { transactionManager.commit(); fail("Transaction should have failed, element has changed in the meantime!"); } catch (RollbackException e) { } transactionManager.begin(); assertNotNull(cache.get("key")); assertEquals("newValue", cache.get("key").getValue()); transactionManager.commit(); } |
### Question:
CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { LOG.debug("CacheManager already shutdown"); return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } if (cacheManagerTimer != null) { cacheManagerTimer.cancel(); cacheManagerTimer.purge(); } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); for (Ehcache cache : ehcaches.values()) { if (cache != null) { cache.dispose(); } } defaultCache.dispose(); status = Status.STATUS_SHUTDOWN; if (this == singleton) { singleton = null; } terracottaClient.shutdown(); removeShutdownHook(); } } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource( "/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } int endingThreadCount; int tries = 0; do { Thread.sleep(500); endingThreadCount = countThreads(); } while (tries++ < 5 || endingThreadCount >= startingThreadCount + 2); assertTrue(endingThreadCount < startingThreadCount + 2); }
@Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); } |
### Question:
CacheManager { public void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache clonedDefaultCache = cloneDefaultCache(cacheName); addCache(clonedDefaultCache); for (Ehcache ehcache : createDefaultCacheDecorators(clonedDefaultCache)) { addOrReplaceDecoratedCache(clonedDefaultCache, ehcache); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCache() throws CacheException { singletonManager = CacheManager.create(); assertEquals(15, singletonManager.getConfiguration().getCacheConfigurations().size()); singletonManager.addCache("test"); singletonManager.addCache("test2"); assertEquals(17, singletonManager.getConfiguration().getCacheConfigurations().size()); Ehcache cache = singletonManager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = singletonManager.getCacheNames(); boolean match = false; for (String cacheName : cacheNames) { if (cacheName.equals("test")) { match = true; } } assertTrue(match); singletonManager.addCache(""); assertEquals(17, singletonManager.getConfiguration().getCacheConfigurations().size()); }
@Test public void testAddCache() throws CacheException { singletonManager = CacheManager.create(); singletonManager.addCache("test"); singletonManager.addCache("test2"); Ehcache cache = singletonManager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = singletonManager.getCacheNames(); boolean match = false; for (String cacheName : cacheNames) { if (cacheName.equals("test")) { match = true; } } assertTrue(match); singletonManager.addCache(""); } |
### Question:
Element implements Serializable, Cloneable { public final boolean isSerializable() { return isKeySerializable() && (value instanceof Serializable || value == null) && elementEvictionData.canParticipateInSerialization(); } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime, final long nextToLastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime,
final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan,
final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value,
final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); final Serializable getKey(); final Object getObjectKey(); final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); ElementEvictionData getElementEvictionData(); void setElementEvictionData(ElementEvictionData elementEvictionData); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); Set<String> getGroupKeys(); void setGroupKeys(Set<String> groupKeys); boolean hasGroupKeys(); boolean addGroupKey(String groupKey); boolean removeGroupKey(String groupKey); }### Answer:
@Test public void testIsSerializable() { Element element = new Element(null, null); assertTrue(element.isSerializable()); Element elementWithNullValue = new Element("1", null); assertTrue(elementWithNullValue.isSerializable()); Element elementWithNullKey = new Element(null, "1"); assertTrue(elementWithNullValue.isSerializable()); Element elementWithObjectKey = new Element(new Object(), "1"); assertTrue(elementWithNullValue.isSerializable()); } |
### Question:
Element implements Serializable, Cloneable { @Override public final boolean equals(final Object object) { if (object == null || !(object instanceof Element)) { return false; } Element element = (Element) object; if (key == null || element.getObjectKey() == null) { return false; } return key.equals(element.getObjectKey()); } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime, final long nextToLastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime,
final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan,
final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value,
final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); final Serializable getKey(); final Object getObjectKey(); final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); ElementEvictionData getElementEvictionData(); void setElementEvictionData(ElementEvictionData elementEvictionData); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); Set<String> getGroupKeys(); void setGroupKeys(Set<String> groupKeys); boolean hasGroupKeys(); boolean addGroupKey(String groupKey); boolean removeGroupKey(String groupKey); }### Answer:
@Test public void testEquals() { Element element = new Element("key", "value"); assertFalse(element.equals("dog")); assertTrue(element.equals(element)); assertFalse(element.equals(null)); assertFalse(element.equals(new Element("cat", "hat"))); } |
### Question:
SelfPopulatingCache extends BlockingCache { public void refresh() throws CacheException { refresh(true); } SelfPopulatingCache(final Ehcache cache, final CacheEntryFactory factory); @Override Element get(final Object key); void refresh(); void refresh(boolean quiet); Element refresh(Object key); Element refresh(Object key, boolean quiet); }### Answer:
@Test public void testRefresh() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new SelfPopulatingCache(cache, factory); assertEquals(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(1, factory.getCount()); selfPopulatingCache.refresh(); assertEquals(2, factory.getCount()); assertEquals(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(2, factory.getCount()); }
@Test public void testRefresh() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new SelfPopulatingCache(cache, factory); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(1, factory.getCount()); selfPopulatingCache.refresh(); assertEquals(2, factory.getCount()); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(2, factory.getCount()); } |
### Question:
CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); return ehcaches.get(name) instanceof Cache ? (Cache) ehcaches.get(name) : null; } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testGetCache() throws CacheException { CacheManager manager = new CacheManager(new Configuration().cache(new CacheConfiguration("foo", 100))); try { assertNotNull(manager.getCache("foo")); } finally { manager.shutdown(); } } |
### Question:
CacheManager { public synchronized void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); configuration.getCacheConfigurations().remove(cacheName); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testRemoveCache() throws CacheException { Configuration config = new Configuration().cache(new CacheConfiguration("foo", 100)); CacheManager manager = new CacheManager(config); try { assertEquals(1, manager.getConfiguration().getCacheConfigurations().size()); assertNotNull(manager.getCache("foo")); manager.removeCache("foo"); assertNull(manager.getCache("foo")); assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); manager.removeCache(null); manager.removeCache(""); assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); } finally { manager.shutdown(); } } |
### Question:
CacheManager { public synchronized void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache clonedDefaultCache = cloneDefaultCache(cacheName); if (clonedDefaultCache == null) { throw new CacheException(NO_DEFAULT_CACHE_ERROR_MSG); } addCache(clonedDefaultCache); for (Ehcache ehcache : createDefaultCacheDecorators(clonedDefaultCache)) { addOrReplaceDecoratedCache(clonedDefaultCache, ehcache); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCache() throws CacheException { Configuration config = new Configuration().defaultCache(new CacheConfiguration().maxElementsInMemory(0)); CacheManager manager = new CacheManager(config); try { assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); manager.addCache("test"); manager.addCache("test2"); assertEquals(2, manager.getConfiguration().getCacheConfigurations().size()); Ehcache cache = manager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = manager.getCacheNames(); boolean match = false; for (String cacheName : cacheNames) { if (cacheName.equals("test")) { match = true; } } assertTrue(match); manager.addCache(""); assertEquals(2, manager.getConfiguration().getCacheConfigurations().size()); } finally { manager.shutdown(); } } |
### Question:
CacheManager { public synchronized Ehcache addCacheIfAbsent(final Ehcache cache) { checkStatus(); return cache == null ? null : addCacheNoCheck(cache, false); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCacheIfAbsent() { Configuration config = new Configuration().defaultCache(new CacheConfiguration().maxElementsInMemory(100)); CacheManager manager = new CacheManager(config); try { manager.addCache("present"); assertThat(manager.addCacheIfAbsent(new Cache(new CacheConfiguration("present", 1000))), sameInstance(manager.getEhcache("present"))); Ehcache theCache = new Cache(new CacheConfiguration("absent", 1000)); Ehcache cache = manager.addCacheIfAbsent(theCache); assertNotNull(cache); assertThat(cache, sameInstance(theCache)); assertThat(cache.getName(), is("absent")); Ehcache other = new Cache(new CacheConfiguration(cache.getName(), 1000)); Ehcache actual = manager.addCacheIfAbsent(other); assertThat(actual, notNullValue()); assertThat(actual, not(sameInstance(other))); assertThat(actual, sameInstance(cache)); Ehcache newCache = new Cache(new CacheConfiguration(cache.getName(), 1000)); manager.removeCache(actual.getName()); actual = manager.addCacheIfAbsent(newCache); assertThat(actual, notNullValue()); assertThat(actual, not(sameInstance(cache))); assertThat(actual, sameInstance(newCache)); assertThat(manager.addCacheIfAbsent(new Cache(new CacheConfiguration(actual.getName(), 1000))), sameInstance(actual)); assertThat(manager.addCacheIfAbsent((Ehcache) null), nullValue()); } finally { manager.shutdown(); } } |
### Question:
ManagementService implements CacheManagerEventListener { public void init() throws CacheException { CacheManager cacheManager = new CacheManager(backingCacheManager); try { registerCacheManager(cacheManager); List caches = cacheManager.getCaches(); for (int i = 0; i < caches.size(); i++) { Cache cache = (Cache) caches.get(i); registerCachesIfRequired(cache); registerCacheStatisticsIfRequired(cache); registerCacheConfigurationIfRequired(cache); } } catch (Exception e) { throw new CacheException(e); } status = Status.STATUS_ALIVE; backingCacheManager.getCacheManagerEventListenerRegistry().registerListener(this); } ManagementService(net.sf.ehcache.CacheManager cacheManager,
MBeanServer mBeanServer,
boolean registerCacheManager,
boolean registerCaches,
boolean registerCacheConfigurations,
boolean registerCacheStatistics); static void registerMBeans(
net.sf.ehcache.CacheManager cacheManager,
MBeanServer mBeanServer,
boolean registerCacheManager,
boolean registerCaches,
boolean registerCacheConfigurations,
boolean registerCacheStatistics); void init(); Status getStatus(); void dispose(); void notifyCacheAdded(String cacheName); void notifyCacheRemoved(String cacheName); }### Answer:
@Test public void testRegistrationServiceFourTrueUsing14MBeanServerWithConstructorInjection() throws Exception { mBeanServer = create14MBeanServer(); ManagementService managementService = new ManagementService(manager, mBeanServer, true, true, true, true); managementService.init(); assertEquals(OBJECTS_IN_TEST_EHCACHE, mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null).size()); } |
### Question:
ManagementService implements CacheManagerEventListener { private void registerCacheManager(CacheManager cacheManager) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { if (registerCacheManager) { mBeanServer.registerMBean(cacheManager, cacheManager.getObjectName()); } } ManagementService(net.sf.ehcache.CacheManager cacheManager,
MBeanServer mBeanServer,
boolean registerCacheManager,
boolean registerCaches,
boolean registerCacheConfigurations,
boolean registerCacheStatistics); static void registerMBeans(
net.sf.ehcache.CacheManager cacheManager,
MBeanServer mBeanServer,
boolean registerCacheManager,
boolean registerCaches,
boolean registerCacheConfigurations,
boolean registerCacheStatistics); void init(); Status getStatus(); void dispose(); void notifyCacheAdded(String cacheName); void notifyCacheRemoved(String cacheName); }### Answer:
@Test public void testRegisterCacheManager() throws Exception { Ehcache ehcache = new net.sf.ehcache.Cache("testNoOverflowToDisk", 1, false, true, 500, 200); manager.addCache(ehcache); ehcache.put(new Element("key1", "value1")); ehcache.put(new Element("key2", "value1")); assertNull(ehcache.get("key1")); assertNotNull(ehcache.get("key2")); ObjectName name = new ObjectName("net.sf.ehcache:type=CacheManager,name=1"); CacheManager cacheManager = new CacheManager(manager); mBeanServer.registerMBean(cacheManager, name); mBeanServer.unregisterMBean(name); name = new ObjectName("net.sf.ehcache:type=CacheManager.Cache,CacheManager=1,name=testOverflowToDisk"); mBeanServer.registerMBean(new Cache(ehcache), name); mBeanServer.unregisterMBean(name); name = new ObjectName("net.sf.ehcache:type=CacheManager.Cache,CacheManager=1,name=sampleCache1"); mBeanServer.registerMBean(new Cache(manager.getCache("sampleCache1")), name); mBeanServer.unregisterMBean(name); } |
### Question:
SelfPopulatingCache extends BlockingCache { public void refresh() throws CacheException { Exception exception = null; Object keyWithException = null; final Collection keys = getKeys(); if (LOG.isLoggable(Level.FINE)) { LOG.fine(getName() + ": found " + keys.size() + " keys to refresh"); } for (Iterator iterator = keys.iterator(); iterator.hasNext();) { final Object key = iterator.next(); try { Ehcache backingCache = getCache(); final Element element = backingCache.getQuiet(key); if (element == null) { if (LOG.isLoggable(Level.FINE)) { LOG.fine(getName() + ": entry with key " + key + " has been removed - skipping it"); } continue; } refreshElement(element, backingCache); } catch (final Exception e) { LOG.log(Level.WARNING, getName() + "Could not refresh element " + key, e); exception = e; } } if (exception != null) { throw new CacheException(exception.getMessage() + " on refresh with key " + keyWithException); } } SelfPopulatingCache(final Ehcache cache, final CacheEntryFactory factory); Element get(final Object key); void refresh(); }### Answer:
@Test public void testRefresh() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new SelfPopulatingCache(cache, factory); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(1, factory.getCount()); selfPopulatingCache.refresh(); assertEquals(2, factory.getCount()); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(2, factory.getCount()); } |
### Question:
UpdatingSelfPopulatingCache extends SelfPopulatingCache { public Element get(final Object key) throws LockTimeoutException { try { Ehcache backingCache = getCache(); Element element = backingCache.get(key); if (element == null) { element = super.get(key); } else { Mutex lock = stripedMutex.getMutexForKey(key); try { lock.acquire(); update(key); } finally { lock.release(); } } return element; } catch (final Throwable throwable) { put(new Element(key, null)); throw new LockTimeoutException("Could not fetch object for cache entry with key \"" + key + "\".", throwable); } } UpdatingSelfPopulatingCache(Ehcache cache, final UpdatingCacheEntryFactory factory); Element get(final Object key); void refresh(); }### Answer:
@Test public void testFetchAndUpdate() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new UpdatingSelfPopulatingCache(cache, factory); Element element = selfPopulatingCache.get(null); element = selfPopulatingCache.get("key"); assertSame(value, element.getObjectValue()); assertEquals(2, factory.getCount()); Object actualValue = selfPopulatingCache.get("key").getObjectValue(); assertSame(value, actualValue); assertEquals(3, factory.getCount()); actualValue = selfPopulatingCache.get("key").getObjectValue(); assertSame(value, actualValue); assertEquals(4, factory.getCount()); }
@Test public void testFetchFail() throws Exception { final Exception exception = new Exception("Failed."); final UpdatingCacheEntryFactory factory = new UpdatingCacheEntryFactory() { public Object createEntry(final Object key) throws Exception { throw exception; } public void updateEntryValue(Object key, Object value) throws Exception { throw exception; } }; selfPopulatingCache = new UpdatingSelfPopulatingCache(cache, factory); try { selfPopulatingCache.get("key"); fail(); } catch (final Exception e) { Thread.sleep(20); assertEquals("Could not fetch object for cache entry with key \"key\".", e.getMessage()); } } |
### Question:
ClusteredStore implements TerracottaStore, StoreListener { @Override public void dispose() { dropLeaderStatus(); topology.removeTopologyListener(eventListenersRefresher); backend.removeListener(evictionListener); backend.disposeLocally(); cacheConfigChangeBridge.disconnectConfigs(); toolkitInstanceFactory.removeNonStopConfigforCache(cache); } ClusteredStore(ToolkitInstanceFactory toolkitInstanceFactory, Ehcache cache, CacheCluster topology); String getFullyQualifiedCacheName(); @Override void recalculateSize(Object key); @Override synchronized void addStoreListener(StoreListener listener); @Override synchronized void removeStoreListener(StoreListener listener); @Override void clusterCoherent(final boolean clusterCoherent); @Override boolean put(Element element); @Override boolean putWithWriter(Element element, CacheWriterManager writerManager); @Override void putAll(Collection<Element> elements); @Override Element get(Object key); @Override Element getQuiet(Object key); @Override List getKeys(); @Override Element remove(Object key); @Override void removeAll(Collection<?> keys); @Override Element removeWithWriter(Object key, CacheWriterManager writerManager); @Override void removeAll(); @Override Element putIfAbsent(Element element); @Override Element removeElement(Element element, ElementValueComparator comparator); @Override boolean replace(Element old, Element element, ElementValueComparator comparator); @Override Element replace(Element element); @Override void dispose(); @Override int getSize(); @Override @Statistic(name = "size", tags = "local-heap") int getInMemorySize(); @Override @Statistic(name = "size", tags = "local-offheap") int getOffHeapSize(); @Override int getOnDiskSize(); @Override void quickClear(); @Override @Statistic(name = "size", tags = "remote") int quickSize(); @Override int getTerracottaClusteredSize(); @Override @Statistic(name = "size-in-bytes", tags = "local-heap") long getInMemorySizeInBytes(); @Override @Statistic(name = "size-in-bytes", tags = "local-offheap") long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override boolean hasAbortedSizeOf(); @Override Status getStatus(); @Override boolean containsKey(Object key); @Override boolean containsKeyOnDisk(Object key); @Override boolean containsKeyOffHeap(Object key); @Override boolean containsKeyInMemory(Object key); @Override void expireElements(); @Override void flush(); @Override boolean bufferFull(); @Override Policy getInMemoryEvictionPolicy(); @Override void setInMemoryEvictionPolicy(Policy policy); @Override Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); @Override Object getMBean(); @Override void setAttributeExtractors(Map<String, AttributeExtractor> extractors); @Override Results executeQuery(StoreQuery query); @Override Set<Attribute> getSearchAttributes(); @Override Attribute<T> getSearchAttribute(String attributeName); @Override Map<Object, Element> getAllQuiet(Collection<?> keys); @Override Map<Object, Element> getAll(Collection<?> keys); String generatePortableKeyFor(final Object obj); @Override Element unsafeGet(Object key); @Override Set getLocalKeys(); @Override TransactionalMode getTransactionalMode(); boolean isSearchable(); String getLeader(); @Override WriteBehind createWriteBehind(); @Override synchronized void notifyCacheEventListenersChanged(); }### Answer:
@Test public void testDispose() throws Exception { clusteredStore.dispose(); verify(toolkitCacheInternal).disposeLocally(); verify(cacheCluster).removeTopologyListener(any(ClusterTopologyListener.class)); verify(toolkitCacheInternal).removeListener(any(ToolkitCacheListener.class)); } |
### Question:
DfltSamplerRepositoryService implements ManagementServerLifecycle,
EntityResourceFactory, CacheManagerService, CacheService, AgentService { @Override public Collection<CacheStatisticSampleEntity> createCacheStatisticSampleEntity(Set<String> cacheManagerNames, Set<String> cacheNames, Set<String> sampleNames) { CacheStatisticSampleEntityBuilder builder = CacheStatisticSampleEntityBuilder.createWith(sampleNames); cacheManagerSamplerRepoLock.readLock().lock(); List<SamplerRepoEntry> disabledSamplerRepoEntries = new ArrayList<SamplerRepoEntry>(); try { if (cacheManagerNames == null) { for (Map.Entry<String, SamplerRepoEntry> entry : cacheManagerSamplerRepo.entrySet()) { enableNonStopFor(entry.getValue(), false); disabledSamplerRepoEntries.add(entry.getValue()); for (CacheSampler sampler : entry.getValue().getComprehensiveCacheSamplers(cacheNames)) { builder.add(sampler, entry.getKey()); } } } else { for (String cmName : cacheManagerNames) { SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cmName); if (entry != null) { enableNonStopFor(entry, false); disabledSamplerRepoEntries.add(entry); for (CacheSampler sampler : entry.getComprehensiveCacheSamplers(cacheNames)) { builder.add(sampler, cmName); } } } } return builder.build(); } finally { for (SamplerRepoEntry samplerRepoEntry : disabledSamplerRepoEntries) { enableNonStopFor(samplerRepoEntry, true); } cacheManagerSamplerRepoLock.readLock().unlock(); } } DfltSamplerRepositoryService(ManagementRESTServiceConfiguration configuration,
RemoteAgentEndpointImpl remoteAgentEndpoint); @Override void dispose(); @Override void register(CacheManager cacheManager); @Override void unregister(CacheManager cacheManager); @Override boolean hasRegistered(); @Override Collection<CacheManagerEntity> createCacheManagerEntities(Set<String> cacheManagerNames,
Set<String> attributes); @Override Collection<CacheManagerConfigEntity> createCacheManagerConfigEntities(Set<String> cacheManagerNames); @Override Collection<CacheEntity> createCacheEntities(Set<String> cacheManagerNames,
Set<String> cacheNames,
Set<String> attributes); @Override Collection<CacheConfigEntity> createCacheConfigEntities(Set<String> cacheManagerNames,
Set<String> cacheNames); @Override Collection<CacheStatisticSampleEntity> createCacheStatisticSampleEntity(Set<String> cacheManagerNames,
Set<String> cacheNames,
Set<String> sampleNames); @Override void createOrUpdateCache(String cacheManagerName,
String cacheName,
CacheEntity resource); @Override void clearCache(String cacheManagerName,
String cacheName); @Override void updateCacheManager(String cacheManagerName,
CacheManagerEntity resource); @Override Collection<QueryResultsEntity> executeQuery(String cacheManagerName, String queryString); @Override Collection<AgentEntity> getAgents(Set<String> ids); @Override Collection<AgentMetadataEntity> getAgentsMetadata(Set<String> ids); static final String AGENCY; }### Answer:
@Test public void testCreateCacheStatisticSampleEntityDisablesNonStop() throws Exception { repositoryService.createCacheStatisticSampleEntity(Collections.singleton("testCacheManager"), Collections.singleton("testCache1"), Collections.singleton("Size")); verify(clusteredInstanceFactory, times(2)).enableNonStopForCurrentThread(anyBoolean()); } |
### Question:
BlockingCache implements Ehcache { protected Ehcache getCache() { return cache; } BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); }### Answer:
@Test public void testThrashBlockingCache() throws Exception { Ehcache cache = manager.getCache("sampleCache1"); blockingCache = new BlockingCache(cache); long duration = thrashCache(blockingCache, 50, 500L, 1000L); LOG.log(Level.FINE, "Thrash Duration:" + duration); }
@Test public void testThrashBlockingCache() throws Exception { Ehcache cache = manager.getCache("sampleCache1"); blockingCache = new BlockingCache(cache); long duration = thrashCache(blockingCache, 50, 500L, 1000L); LOG.debug("Thrash Duration:" + duration); } |
### Question:
BlockingCache implements Ehcache { public Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument) throws CacheException { throw new CacheException("This method is not appropriate for a Blocking Cache"); } BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); }### Answer:
@Test public void testGetWithLoader() { super.testGetWithLoader(); } |
### Question:
CachesResource { @GET public Caches getCaches() { LOG.info("GET Caches"); String[] cacheNames = CacheManager.getInstance().getCacheNames(); List<Cache> cacheList = new ArrayList<Cache>(); for (String cacheName : cacheNames) { URI cacheUri = uriInfo.getAbsolutePathBuilder().path(cacheName).build().normalize(); Cache cache = new Cache(cacheName, cacheUri.toString()); cacheList.add(cache); } return new Caches(cacheList); } @Path("{cache}") CacheResource getCacheResource(@PathParam("cache") String cache); @GET Caches getCaches(); }### Answer:
@Test public void testGetCaches() throws IOException, ParserConfigurationException, SAXException { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { manager.addCache(cacheName); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testAddCache() throws CacheException_Exception, NoSuchCacheException_Exception, IllegalStateException_Exception, ObjectExistsException_Exception { cacheService.addCache("newcache1"); Cache cache = cacheService.getCache("newcache1"); assertNotNull(cache); try { cacheService.addCache("newcache1"); } catch (SOAPFaultException e) { assertTrue(e.getCause().getMessage().indexOf("Cache newcache1 already exists") != -1); } }
@Test public void testAddCache() throws Exception { cacheService.addCache("newcache1"); Cache cache = cacheService.getCache("newcache1"); assertNotNull(cache); try { cacheService.addCache("newcache1"); } catch (SOAPFaultException e) { assertTrue(e.getCause().getMessage().indexOf("Cache newcache1 already exists") != -1); } } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public void removeCache(String cacheName) throws IllegalStateException { manager.removeCache(cacheName); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testRemoveCache() throws CacheException_Exception, NoSuchCacheException_Exception, IllegalStateException_Exception, ObjectExistsException_Exception { cacheService.addCache("newcache2"); Cache cache = cacheService.getCache("newcache2"); assertNotNull(cache); cacheService.removeCache("newcache2"); cache = cacheService.getCache("newcache2"); assertNull(cache); cacheService.removeCache("newcache2"); cache = cacheService.getCache("newcache2"); assertNull(cache); }
@Test public void testRemoveCache() throws Exception { cacheService.addCache("newcache2"); Cache cache = cacheService.getCache("newcache2"); assertNotNull(cache); cacheService.removeCache("newcache2"); cache = cacheService.getCache("newcache2"); assertNull(cache); cacheService.removeCache("newcache2"); cache = cacheService.getCache("newcache2"); assertNull(cache); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public void put(String cacheName, Element element) throws NoSuchCacheException, CacheException { net.sf.ehcache.Cache cache = lookupCache(cacheName); cache.put(element.getEhcacheElement()); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testCachePutNull() throws CacheException_Exception, NoSuchCacheException_Exception, IllegalStateException_Exception { Element element = new Element(); element.setKey("1"); cacheService.put("sampleCache1", element); element = getElementFromCache(); boolean equals = Arrays.equals(null, element.getValue()); assertTrue(equals); }
@Test public void testCachePutNull() throws Exception, NoSuchCacheException_Exception, IllegalStateException_Exception { Element element = new Element(); element.setKey("1"); cacheService.put("sampleCache1", element); element = getElementFromCache(); boolean equals = Arrays.equals(null, element.getValue()); assertTrue(equals); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public Statistics getStatistics(String cacheName) throws IllegalStateException { net.sf.ehcache.Cache cache = lookupCache(cacheName); return new Statistics(cache.getStatistics()); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testGetStatistics() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { cacheService.clearStatistics("sampleCache1"); Statistics statistics = cacheService.getStatistics("sampleCache1"); assertEquals(0L, statistics.getCacheHits()); putElementIntoCache(); getElementFromCache(); statistics = cacheService.getStatistics("sampleCache1"); assertEquals(1L, statistics.getCacheHits()); assertTrue(statistics.getAverageGetTime() >= 0); assertEquals(0L, statistics.getEvictionCount()); assertEquals(1L, statistics.getInMemoryHits()); assertEquals(0L, statistics.getOnDiskHits()); assertEquals(StatisticsAccuracy.STATISTICS_ACCURACY_BEST_EFFORT, statistics.getStatisticsAccuracy()); }
@Test public void testGetStatistics() throws Exception { cacheService.clearStatistics("sampleCache1"); Statistics statistics = cacheService.getStatistics("sampleCache1"); assertEquals(0L, statistics.getCacheHits()); putElementIntoCache(); getElementFromCache(); statistics = cacheService.getStatistics("sampleCache1"); assertEquals(1L, statistics.getCacheHits()); assertTrue(statistics.getAverageGetTime() >= 0); assertEquals(0L, statistics.getEvictionCount()); assertEquals(1L, statistics.getInMemoryHits()); assertEquals(0L, statistics.getOnDiskHits()); assertEquals(StatisticsAccuracy.STATISTICS_ACCURACY_BEST_EFFORT, statistics.getStatisticsAccuracy()); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public void clearStatistics(String cacheName) { net.sf.ehcache.Cache cache = lookupCache(cacheName); cache.clearStatistics(); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testClearStatistics() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { putElementIntoCache(); getElementFromCache(); cacheService.clearStatistics("sampleCache1"); Statistics statistics = cacheService.getStatistics("sampleCache1"); assertEquals(0L, statistics.getCacheHits()); }
@Test public void testClearStatistics() throws Exception { putElementIntoCache(); getElementFromCache(); cacheService.clearStatistics("sampleCache1"); Statistics statistics = cacheService.getStatistics("sampleCache1"); assertEquals(0L, statistics.getCacheHits()); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public Element getWithLoader(String cacheName, String key) throws NoSuchCacheException { net.sf.ehcache.Cache cache = lookupCache(cacheName); net.sf.ehcache.Element element = cache.getWithLoader(key, null, null); if (element != null) { return new Element(element); } else { return null; } } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod StatisticsAccuracy getStatisticsAccuracy(String cacheName); @WebMethod void clearStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testGetWithLoad() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { cacheService.getWithLoader("sampleCache1", "2"); } |
### Question:
ConcurrencyUtil { public static int selectLock(final Object key, int numberOfLocks) throws CacheException { int number = numberOfLocks & (numberOfLocks - 1); if (number != 0) { throw new CacheException("Lock number must be a power of two: " + numberOfLocks); } if (key == null) { return 0; } else { int hash = hash(key) & (numberOfLocks - 1); return hash; } } private ConcurrencyUtil(); static int hash(Object object); static int selectLock(final Object key, int numberOfLocks); }### Answer:
@Test public void testStripingDistribution() { int[] lockIndexes = new int[2048]; for (int i = 0; i < 20480 * 3; i++) { String key = "" + i * 3 / 2 + i; key += key.hashCode(); int lock = ConcurrencyUtil.selectLock(key, 2048); lockIndexes[lock]++; } int outliers = 0; for (int i = 0; i < 2048; i++) { if (20 <= lockIndexes[i] && lockIndexes[i] <= 40) { continue; } LOG.log(Level.INFO, i + ": " + lockIndexes[i]); outliers++; } assertTrue(outliers <= 128); }
@Test public void testStripingDistribution() { int[] lockIndexes = new int[2048]; for (int i = 0; i < 20480 * 3; i++) { String key = "" + i * 3 / 2 + i; key += key.hashCode(); int lock = ConcurrencyUtil.selectLock(key, 2048); lockIndexes[lock]++; } int outliers = 0; for (int i = 0; i < 2048; i++) { if (20 <= lockIndexes[i] && lockIndexes[i] <= 40) { continue; } LOG.info(i + ": " + lockIndexes[i]); outliers++; } assertTrue(outliers <= 128); }
@Test public void testNullKey() { ConcurrencyUtil.selectLock(null, 2048); ConcurrencyUtil.selectLock("", 2048); }
@Test public void testEvenLockNumber() { try { ConcurrencyUtil.selectLock("anything", 100); } catch (CacheException e) { } } |
### Question:
Status implements Serializable { public boolean equals(Object object) { if (!(object instanceof Status)) { return false; } return ((Status) object).intValue == intValue; } private Status(int intValue, String name); String toString(); static Status convertIntToStatus(int statusAsInt); int intValue(); boolean equals(Object object); boolean equals(Status status); int hashCode(); static final Status STATUS_UNINITIALISED; static final Status STATUS_ALIVE; static final Status STATUS_SHUTDOWN; }### Answer:
@Test public void testEqualsPerformance() { StopWatch stopWatch = new StopWatch(); stopWatch.getElapsedTime(); Status status2 = Status.STATUS_SHUTDOWN; for (int i = 0; i < 10000; i++) { status1.equals(status2); } stopWatch.getElapsedTime(); for (int i = 0; i < 10000; i++) { status1.equals(status2); } long statusCompareTime = stopWatch.getElapsedTime(); LOG.log(Level.INFO, "Time to do equals(Status): " + statusCompareTime); assertTrue("Status compare is greater than permitted time", statusCompareTime < 35); }
@Test public void testObjectEqualsPerformance() { StopWatch stopWatch = new StopWatch(); stopWatch.getElapsedTime(); Object object = new Object(); for (int i = 0; i < 10000; i++) { status1.equals(object); } stopWatch.getElapsedTime(); for (int i = 0; i < 10000; i++) { status1.equals(object); } long objectCompareTime = stopWatch.getElapsedTime(); LOG.log(Level.INFO, "Time to do equals(Object): " + objectCompareTime); assertTrue("Status compare is greater than permitted time", objectCompareTime < 25); }
@Test public void testEqualsPerformance() { StopWatch stopWatch = new StopWatch(); stopWatch.getElapsedTime(); Status status2 = Status.STATUS_SHUTDOWN; for (int i = 0; i < 10000; i++) { status1.equals(status2); } stopWatch.getElapsedTime(); for (int i = 0; i < 10000; i++) { status1.equals(status2); } long statusCompareTime = stopWatch.getElapsedTime(); LOG.info("Time to do equals(Status): " + statusCompareTime); assertTrue("Status compare is greater than permitted time", statusCompareTime < 35); }
@Test public void testObjectEqualsPerformance() { StopWatch stopWatch = new StopWatch(); stopWatch.getElapsedTime(); Object object = new Object(); for (int i = 0; i < 10000; i++) { status1.equals(object); } stopWatch.getElapsedTime(); for (int i = 0; i < 10000; i++) { status1.equals(object); } long objectCompareTime = stopWatch.getElapsedTime(); LOG.info("Time to do equals(Object): " + objectCompareTime); assertTrue("Status compare is greater than permitted time", objectCompareTime < 25); } |
### Question:
CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "CacheManager already shutdown"); } return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); Collection cacheSet = ehcaches.values(); for (Iterator iterator = cacheSet.iterator(); iterator.hasNext();) { Ehcache cache = (Ehcache) iterator.next(); if (cache != null) { cache.dispose(); } } defaultCache.dispose(); status = Status.STATUS_SHUTDOWN; if (this == singleton) { singleton = null; } removeShutdownHook(); } } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); void setName(String name); String toString(); String getDiskStorePath(); static final List ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource("/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } Thread.sleep(300); int endingThreadCount = countThreads(); assertTrue(endingThreadCount < startingThreadCount + 2); }
@Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); } |
### Question:
CacheManager { public static CacheManager create() throws CacheException { if (singleton != null) { return singleton; } synchronized (CacheManager.class) { if (singleton == null) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Creating new CacheManager with default config"); } singleton = new CacheManager(); } else { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Attempting to create an existing singleton. Existing singleton returned."); } } return singleton; } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); void setName(String name); String toString(); String getDiskStorePath(); static final List ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testCacheManagerThreads() throws CacheException, InterruptedException { singletonManager = CacheManager.create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml"); int threads = countThreads(); assertTrue("More than 75 threads: " + threads, countThreads() <= 75); } |
### Question:
CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); return (Cache) caches.get(name); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); void setName(String name); String toString(); String getDiskStorePath(); static final List ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testGetCache() throws CacheException { instanceManager = CacheManager.create(); Ehcache cache = instanceManager.getCache("sampleCache1"); assertNotNull(cache); } |
### Question:
CacheManager { public void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = (Ehcache) ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } caches.remove(cacheName); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); void setName(String name); String toString(); String getDiskStorePath(); static final List ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testRemoveCache() throws CacheException { singletonManager = CacheManager.create(); Ehcache cache = singletonManager.getCache("sampleCache1"); assertNotNull(cache); singletonManager.removeCache("sampleCache1"); cache = singletonManager.getCache("sampleCache1"); assertNull(cache); singletonManager.removeCache(null); singletonManager.removeCache(""); } |
### Question:
CacheManager { public void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache cache = null; try { cache = (Ehcache) defaultCache.clone(); } catch (CloneNotSupportedException e) { throw new CacheException("Failure adding cache. Initial cause was " + e.getMessage(), e); } if (cache != null) { cache.setName(cacheName); } addCache(cache); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); void setName(String name); String toString(); String getDiskStorePath(); static final List ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCache() throws CacheException { singletonManager = CacheManager.create(); singletonManager.addCache("test"); singletonManager.addCache("test2"); Ehcache cache = singletonManager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = singletonManager.getCacheNames(); boolean match = false; for (int i = 0; i < cacheNames.length; i++) { String cacheName = cacheNames[i]; if (cacheName.equals("test")) { match = true; } } assertTrue(match); singletonManager.addCache(""); } |
### Question:
Statistics implements Serializable { public void clearStatistics() { if (cache == null) { throw new IllegalStateException("This statistics object no longer references a Cache."); } cache.clearStatistics(); } Statistics(Ehcache cache, int statisticsAccuracy, long cacheHits, long onDiskHits, long inMemoryHits,
long misses, long size, float averageGetTime, long evictionCount, long memoryStoreSize,
long diskStoreSize); void clearStatistics(); long getCacheHits(); long getInMemoryHits(); long getOnDiskHits(); long getCacheMisses(); long getObjectCount(); long getMemoryStoreObjectCount(); long getDiskStoreObjectCount(); int getStatisticsAccuracy(); String getStatisticsAccuracyDescription(); String getAssociatedCacheName(); Ehcache getAssociatedCache(); final String toString(); float getAverageGetTime(); long getEvictionCount(); static final int STATISTICS_ACCURACY_NONE; static final int STATISTICS_ACCURACY_BEST_EFFORT; static final int STATISTICS_ACCURACY_GUARANTEED; }### Answer:
@Test public void testClearStatistics() throws InterruptedException { Cache cache = new Cache("test", 1, true, false, 5, 2); manager.addCache(cache); cache.put(new Element("key1", "value1")); cache.put(new Element("key2", "value1")); cache.get("key1"); Statistics statistics = cache.getStatistics(); assertEquals(1, statistics.getCacheHits()); assertEquals(1, statistics.getOnDiskHits()); assertEquals(0, statistics.getInMemoryHits()); assertEquals(0, statistics.getCacheMisses()); statistics.clearStatistics(); statistics = cache.getStatistics(); assertEquals(0, statistics.getCacheHits()); assertEquals(0, statistics.getOnDiskHits()); assertEquals(0, statistics.getInMemoryHits()); assertEquals(0, statistics.getCacheMisses()); } |
### Question:
Element implements Serializable, Cloneable { public final long getSerializedSize() { if (!isSerializable()) { return 0; } long size = 0; ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(bout); oos.writeObject(this); size = bout.size(); return size; } catch (IOException e) { LOG.log(Level.FINE, "Error measuring element size for element with key " + key + ". Cause was: " + e.getMessage()); } finally { try { if (oos != null) { oos.close(); } } catch (Exception e) { LOG.log(Level.SEVERE, "Error closing ObjectOutputStream"); } } return size; } Element(Serializable key, Serializable value, long version); Element(Object key, Object value, long version); Element(Object key, Object value, long version,
long creationTime, long lastAccessTime,
long nextToLastAccessTime, long lastUpdateTime,
long hitCount); Element(Object key, Object value,
Boolean eternal, Integer timeToIdleSeconds, Integer timeToLiveSeconds); Element(Serializable key, Serializable value); Element(Object key, Object value); final Serializable getKey(); final Object getObjectKey(); final Serializable getValue(); final Object getObjectValue(); final boolean equals(Object object); void setTimeToLive(int timeToLiveSeconds); void setTimeToIdle(int timeToIdleSeconds); final int hashCode(); final void setVersion(long version); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final void setCreateTime(); final long getVersion(); final long getLastAccessTime(); final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); final String toString(); final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); long getExpirationTime(); boolean isEternal(); void setEternal(boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); }### Answer:
@Test public void testSerializationPerformanceByteArray() throws CacheException { Serializable key = "key"; ByteArrayOutputStream bout = new ByteArrayOutputStream(); for (int j = 0; j < 10000; j++) { try { bout.write("abcdefghijklmnopqrstv1234567890".getBytes()); } catch (IOException e) { LOG.log(Level.SEVERE, "This should not happen"); } } byte[] value = bout.toByteArray(); Element element = new Element(key, value); StopWatch stopWatch = new StopWatch(); for (int i = 0; i < 100; i++) { element.getSerializedSize(); } long elapsed = stopWatch.getElapsedTime() / 100; LOG.log(Level.INFO, "In-memory size in bytes: " + element.getSerializedSize() + " time to serialize in ms: " + elapsed); assertTrue("Large object clone takes more than than 100ms", elapsed < 100); }
@Test public void testSerializationPerformanceJavaObjects() throws Exception { HashMap map = new HashMap(10000); for (int j = 0; j < 10000; j++) { map.put("key" + j, new String[]{"adfdafs", "asdfdsafa", "sdfasdf"}); } Element element = new Element("key1", map); StopWatch stopWatch = new StopWatch(); for (int i = 0; i < 100; i++) { element.getSerializedSize(); } long elapsed = stopWatch.getElapsedTime() / 100; LOG.log(Level.INFO, "In-memory size in bytes: " + element.getSerializedSize() + " time to serialize in ms: " + elapsed); assertTrue("Large object clone took more than 500ms", elapsed < 500); } |
### Question:
Element implements Serializable, Cloneable { public final boolean isSerializable() { return isKeySerializable() && (value instanceof Serializable || value == null); } Element(Serializable key, Serializable value, long version); Element(Object key, Object value, long version); Element(Object key, Object value, long version,
long creationTime, long lastAccessTime,
long nextToLastAccessTime, long lastUpdateTime,
long hitCount); Element(Object key, Object value,
Boolean eternal, Integer timeToIdleSeconds, Integer timeToLiveSeconds); Element(Serializable key, Serializable value); Element(Object key, Object value); final Serializable getKey(); final Object getObjectKey(); final Serializable getValue(); final Object getObjectValue(); final boolean equals(Object object); void setTimeToLive(int timeToLiveSeconds); void setTimeToIdle(int timeToIdleSeconds); final int hashCode(); final void setVersion(long version); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final void setCreateTime(); final long getVersion(); final long getLastAccessTime(); final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); final String toString(); final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); long getExpirationTime(); boolean isEternal(); void setEternal(boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); }### Answer:
@Test public void testIsSerializable() { Element element = new Element(null, null); assertTrue(element.isSerializable()); Element elementWithNullValue = new Element("1", null); assertTrue(elementWithNullValue.isSerializable()); Element elementWithNullKey = new Element(null, "1"); assertTrue(elementWithNullValue.isSerializable()); Element elementWithObjectKey = new Element(new Object(), "1"); assertTrue(elementWithNullValue.isSerializable()); } |
### Question:
Element implements Serializable, Cloneable { public final boolean equals(Object object) { if (object == null || !(object instanceof Element)) { return false; } Element element = (Element) object; if (key == null || element.getObjectKey() == null) { return false; } return key.equals(element.getObjectKey()); } Element(Serializable key, Serializable value, long version); Element(Object key, Object value, long version); Element(Object key, Object value, long version,
long creationTime, long lastAccessTime,
long nextToLastAccessTime, long lastUpdateTime,
long hitCount); Element(Object key, Object value,
Boolean eternal, Integer timeToIdleSeconds, Integer timeToLiveSeconds); Element(Serializable key, Serializable value); Element(Object key, Object value); final Serializable getKey(); final Object getObjectKey(); final Serializable getValue(); final Object getObjectValue(); final boolean equals(Object object); void setTimeToLive(int timeToLiveSeconds); void setTimeToIdle(int timeToIdleSeconds); final int hashCode(); final void setVersion(long version); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final void setCreateTime(); final long getVersion(); final long getLastAccessTime(); final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); final String toString(); final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); long getExpirationTime(); boolean isEternal(); void setEternal(boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); }### Answer:
@Test public void testEquals() { Element element = new Element("key", "value"); assertFalse(element.equals("dog")); assertTrue(element.equals(element)); assertFalse(element.equals(null)); assertFalse(element.equals(new Element("cat", "hat"))); } |
### Question:
OnHeapCachingTier implements CachingTier<K, V> { @Override public V get(final K key, final Callable<V> source, final boolean updateStats) { Object cachedValue = backEnd.get(key); if (cachedValue == null) { Fault<V> f = new Fault<V>(source); cachedValue = backEnd.putIfAbsent(key, f); if (cachedValue == null && !f.complete) { try { V value = source.call(); if (value == null) { backEnd.remove(key, f); } else { backEnd.replace(key, f, value); } f.complete(value); return value; } catch (Exception e) { backEnd.remove(key, f); f.fail(e); if (e instanceof RuntimeException) { throw (RuntimeException)e; } throw new RuntimeException(e); } } } return getValue(cachedValue); } OnHeapCachingTier(final HeapCacheBackEnd<K, Object> backEnd); @Override V get(final K key, final Callable<V> source, final boolean updateStats); @Override V remove(final K key); @Override void clear(); @Override void addListener(final Listener<K, V> listener); @Override int getInMemorySize(); @Override int getOffHeapSize(); @Override boolean contains(final K key); @Override long getInMemorySizeInBytes(); @Override long getOnDiskSizeInBytes(); }### Answer:
@Test public void testOnlyPopulatesOnce() throws InterruptedException, BrokenBarrierException { final int threadCount = Runtime.getRuntime().availableProcessors() * 2; final CachingTier<String, String> cache = new OnHeapCachingTier<String, String>(new CountBasedBackEnd<String, Object>(threadCount * 2)); final AtomicBoolean failure = new AtomicBoolean(); final AtomicInteger invocationCounter = new AtomicInteger(); final AtomicInteger valuesRead = new AtomicInteger(); final CyclicBarrier barrier = new CyclicBarrier(threadCount + 1); final Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread() { @Override public void run() { try { final int await = barrier.await(); cache.get(KEY, new Callable<String>() { @Override public String call() throws Exception { invocationCounter.incrementAndGet(); return "0x" + Integer.toHexString(await); } }, false); valuesRead.getAndIncrement(); } catch (Exception e) { e.printStackTrace(); failure.set(true); } } }; threads[i].start(); } barrier.await(); for (Thread thread : threads) { thread.join(); } assertThat(failure.get(), is(false)); assertThat(invocationCounter.get(), is(1)); assertThat(valuesRead.get(), is(threadCount)); } |
### Question:
PayloadUtil { public static byte[] gzip(byte[] ungzipped) { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try { final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bytes); gzipOutputStream.write(ungzipped); gzipOutputStream.close(); } catch (IOException e) { LOG.log(Level.SEVERE, "Could not gzip " + ungzipped); } return bytes.toByteArray(); } private PayloadUtil(); static byte[] assembleUrlList(List localCachePeers); static byte[] gzip(byte[] ungzipped); static byte[] ungzip(final byte[] gzipped); static final int MTU; static final String URL_DELIMITER; }### Answer:
@Test public void testMaximumDatagram() throws IOException { String payload = createReferenceString(); final byte[] compressed = PayloadUtil.gzip(payload.getBytes()); int length = compressed.length; LOG.log(Level.INFO, "gzipped size: " + length); assertTrue("Heartbeat too big for one Datagram " + length, length <= 1500); }
@Test public void testGzipSanityAndPerformance() throws IOException, InterruptedException { String payload = createReferenceString(); for (int i = 0; i < 10; i++) { byte[] compressed = PayloadUtil.gzip(payload.getBytes()); assertTrue(compressed.length > 300); Thread.sleep(20); } int hashCode = payload.hashCode(); StopWatch stopWatch = new StopWatch(); for (int i = 0; i < 10000; i++) { if (hashCode != payload.hashCode()) { PayloadUtil.gzip(payload.getBytes()); } } long elapsed = stopWatch.getElapsedTime(); LOG.log(Level.INFO, "Gzip took " + elapsed / 10F + " µs"); } |
### Question:
JCache implements net.sf.jsr107cache.Cache { public void evict() { cache.evictExpiredElements(); } JCache(Ehcache cache); JCache(Ehcache cache, net.sf.jsr107cache.CacheLoader cacheLoader); JCache(Ehcache cache, JCacheLoader cacheLoader); void setCacheLoader(JCacheLoader cacheLoader); void addListener(CacheListener cacheListener); void evict(); Map getAll(Collection keys); Map getAll(Collection keys, Object loaderArgument); CacheLoader getCacheLoader(); CacheEntry getCacheEntry(Object key); CacheStatistics getCacheStatistics(); void load(final Object key); void loadAll(final Collection keys); void loadAll(final Collection keys, final Object loaderArgument); Object peek(Object key); void removeListener(CacheListener cacheListener); int size(); boolean isEmpty(); boolean containsKey(Object key); boolean containsValue(Object value); Object get(Object key); Object get(Object key, Object loaderArgument); Object get(Object key, JCacheLoader loader); Object get(Object key, JCacheLoader loader, Object loaderArgument); Object put(Object key, Object value); Object put(Object key, Object value, int timeToLiveSeconds); Object remove(Object key); void putAll(Map sourceMap); void clear(); Set keySet(); Collection values(); Set entrySet(); void setStatisticsAccuracy(int statisticsAccuracy); Ehcache getBackingCache(); String toString(); }### Answer:
@Test public void testEvict() throws Exception { Ehcache ehcache = new net.sf.ehcache.Cache("testEvict", 1, true, false, 1, 200); manager.addCache(ehcache); Cache cache = new JCache(ehcache); assertTrue(cache.isEmpty()); cache.put("key1", "value1"); cache.put("key2", "value1"); cache.evict(); assertFalse(cache.isEmpty()); Thread.sleep(1020); cache.evict(); assertNull(cache.get("key1")); assertNull(cache.get("key2")); cache.put("key1", "value1"); cache.put("key2", "value1"); Thread.sleep(1020); assertNull(cache.get("key1")); assertNull(cache.get("key2")); }
@Test public void testEvict() throws Exception { Ehcache ehcache = new net.sf.ehcache.Cache("testEvict", 1, true, false, 1, 200); manager.addCache(ehcache); Cache cache = new JCache(ehcache); assertTrue(cache.isEmpty()); cache.put("key1", "value1"); cache.put("key2", "value1"); cache.evict(); assertFalse(cache.isEmpty()); Thread.sleep(1999); cache.evict(); assertNull(cache.get("key1")); assertNull(cache.get("key2")); cache.put("key1", "value1"); cache.put("key2", "value1"); Thread.sleep(1999); assertNull(cache.get("key1")); assertNull(cache.get("key2")); } |
### Question:
JCache implements net.sf.jsr107cache.Cache { public boolean containsValue(Object value) { long start = System.currentTimeMillis(); boolean inCache = cache.isValueInCache(value); long end = System.currentTimeMillis(); if (LOG.isLoggable(Level.WARNING)) { LOG.warning("Performance Warning: containsValue is not recommended. This call took " + (end - start) + " ms"); } return inCache; } JCache(Ehcache cache); JCache(Ehcache cache, net.sf.jsr107cache.CacheLoader cacheLoader); JCache(Ehcache cache, JCacheLoader cacheLoader); void setCacheLoader(JCacheLoader cacheLoader); void addListener(CacheListener cacheListener); void evict(); Map getAll(Collection keys); Map getAll(Collection keys, Object loaderArgument); CacheLoader getCacheLoader(); CacheEntry getCacheEntry(Object key); CacheStatistics getCacheStatistics(); void load(final Object key); void loadAll(final Collection keys); void loadAll(final Collection keys, final Object loaderArgument); Object peek(Object key); void removeListener(CacheListener cacheListener); int size(); boolean isEmpty(); boolean containsKey(Object key); boolean containsValue(Object value); Object get(Object key); Object get(Object key, Object loaderArgument); Object get(Object key, JCacheLoader loader); Object get(Object key, JCacheLoader loader, Object loaderArgument); Object put(Object key, Object value); Object put(Object key, Object value, int timeToLiveSeconds); Object remove(Object key); void putAll(Map sourceMap); void clear(); Set keySet(); Collection values(); Set entrySet(); void setStatisticsAccuracy(int statisticsAccuracy); Ehcache getBackingCache(); String toString(); }### Answer:
@Test public void testContainsValue() throws Exception { Ehcache ehcache = new net.sf.ehcache.Cache("testContainsValue", 2, true, true, 500, 200); manager.addCache(ehcache); Cache cache = new JCache(ehcache); assertFalse(cache.containsValue("value1")); assertFalse(cache.containsValue(null)); cache.put("key1", null); assertFalse(cache.containsValue("value1")); assertTrue(cache.containsValue(null)); cache.put("key2", "value1"); assertTrue(cache.containsValue("value1")); assertTrue(cache.containsValue(null)); assertNull(cache.get("key1")); assertNotNull(cache.get("key2")); } |
### Question:
JCache implements net.sf.jsr107cache.Cache { public void loadAll(final Collection keys) throws CacheException { loadAll(keys, null); } JCache(Ehcache cache); JCache(Ehcache cache, net.sf.jsr107cache.CacheLoader cacheLoader); JCache(Ehcache cache, JCacheLoader cacheLoader); void setCacheLoader(JCacheLoader cacheLoader); void addListener(CacheListener cacheListener); void evict(); Map getAll(Collection keys); Map getAll(Collection keys, Object loaderArgument); CacheLoader getCacheLoader(); CacheEntry getCacheEntry(Object key); CacheStatistics getCacheStatistics(); void load(final Object key); void loadAll(final Collection keys); void loadAll(final Collection keys, final Object loaderArgument); Object peek(Object key); void removeListener(CacheListener cacheListener); int size(); boolean isEmpty(); boolean containsKey(Object key); boolean containsValue(Object value); Object get(Object key); Object get(Object key, Object loaderArgument); Object get(Object key, JCacheLoader loader); Object get(Object key, JCacheLoader loader, Object loaderArgument); Object put(Object key, Object value); Object put(Object key, Object value, int timeToLiveSeconds); Object remove(Object key); void putAll(Map sourceMap); void clear(); Set keySet(); Collection values(); Set entrySet(); void setStatisticsAccuracy(int statisticsAccuracy); Ehcache getBackingCache(); String toString(); }### Answer:
@Test public void testLoadAll() throws InterruptedException, ExecutionException, CacheException { CountingCacheLoader countingCacheLoader = new CountingCacheLoader(); JCache jcache = new JCache(manager.getCache("sampleCache1"), countingCacheLoader); jcache.loadAll(null); List keys = new ArrayList(); for (int i = 0; i < 999; i++) { keys.add(new Integer(i)); } keys.add(null); jcache.put(new Integer(1), ""); jcache.loadAll(keys); Thread.sleep((long) (3000 * StopWatch.getSpeedAdjustmentFactor())); assertEquals(1000, jcache.size()); assertEquals(999, countingCacheLoader.getLoadAllCounter()); }
@Test public void testLoadAll() throws InterruptedException, ExecutionException, CacheException { CountingCacheLoader countingCacheLoader = new CountingCacheLoader(); JCache jcache = new JCache(manager.getCache("sampleCache1"), countingCacheLoader); jcache.loadAll(null); List keys = new ArrayList(); for (int i = 0; i < 999; i++) { keys.add(new Integer(i)); } jcache.put(new Integer(1), ""); jcache.loadAll(keys); Thread.sleep((long) (3000 * StopWatch.getSpeedAdjustmentFactor())); assertEquals(999, jcache.size()); assertEquals(998, countingCacheLoader.getLoadAllCounter()); } |
### Question:
JCacheEntry implements CacheEntry { public boolean isValid() { if (element != null) { return !element.isExpired(); } else { return false; } } JCacheEntry(Element element); Object getKey(); Object getValue(); Object setValue(Object value); long getCost(); long getCreationTime(); long getExpirationTime(); int getHits(); long getLastAccessTime(); long getLastUpdateTime(); long getVersion(); boolean isValid(); }### Answer:
@Test public void testIsValid() throws Exception { Cache cache = getTestCache(); CacheEntry entry = new JCacheEntry(new Element("key1", "value1")); assertEquals(true, entry.isValid()); cache.put(entry.getKey(), entry.getValue()); CacheEntry retrievedEntry = cache.getCacheEntry(entry.getKey()); assertEquals(true, retrievedEntry.isValid()); Thread.sleep(1020); assertEquals(false, retrievedEntry.isValid()); }
@Test public void testIsValid() throws Exception { Cache cache = getTestCache(); CacheEntry entry = new JCacheEntry(new Element("key1", "value1")); assertEquals(true, entry.isValid()); cache.put(entry.getKey(), entry.getValue()); CacheEntry retrievedEntry = cache.getCacheEntry(entry.getKey()); assertEquals(true, retrievedEntry.isValid()); Thread.sleep(1999); assertEquals(false, retrievedEntry.isValid()); } |
### Question:
SlewClock { static long timeMillis() { boolean interrupted = false; try { while (true) { long mono = CURRENT.get(); long wall = getCurrentTime(); if (wall == mono) { OFFSET.remove(); return wall; } else if (wall >= mono) { if (CURRENT.compareAndSet(mono, wall)) { OFFSET.remove(); return wall; } } else { long delta = mono - wall; if (delta < DRIFT_MAXIMAL) { OFFSET.remove(); return mono; } else { Long lastDelta = OFFSET.get(); if (lastDelta == null || delta < lastDelta) { long update = wall - delta; update = update < mono ? mono + 1 : update; if (CURRENT.compareAndSet(mono, update)) { OFFSET.set(Long.valueOf(delta)); return update; } } else { try { long sleep = sleepTime(delta, lastDelta); LOG.trace("{} sleeping for {}ms to adjust for wall-clock drift.", Thread.currentThread(), sleep); Thread.sleep(sleep); } catch (InterruptedException e) { interrupted = true; } } } } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } private SlewClock(); }### Answer:
@Test public void testTimeMillis() throws Throwable { final AtomicLong slewStart = new AtomicLong(); final AtomicLong offset = new AtomicLong(0); final List<Throwable> errors = Collections.synchronizedList(new ArrayList<Throwable>()); TimeProviderLoader.setTimeProvider(new SlewClock.TimeProvider() { public long currentTimeMillis() { return System.currentTimeMillis() - offset.get(); } }); final AtomicBoolean stopped = new AtomicBoolean(false); final AtomicInteger catchingUp = new AtomicInteger(); SlewClockVerifierThread[] threads = new SlewClockVerifierThread[THREADS]; for(int i =0; i < THREADS; i++) { threads[i] = new SlewClockVerifierThread(stopped, catchingUp, errors, slewStart, i == 0); } for (Thread thread : threads) { thread.start(); } Thread.sleep(TimeUnit.SECONDS.toMillis(DURATION)); System.out.println("Going back in time by " + BACK_IN_TIME); slewStart.set(System.currentTimeMillis()); offset.set(BACK_IN_TIME); Thread.sleep(SLOWRUN ? BACK_IN_TIME * 3 : BACK_IN_TIME * 2); stopped.set(true); for (SlewClockVerifierThread thread : threads) { thread.join(); } if(!errors.isEmpty()) { System.err.println("We have " + errors.size() + " error(s) here!"); throw errors.get(0); } assertThat(catchingUp.get(), is(THREADS)); } |
### Question:
XATransactionalStore extends AbstractStore { public Element removeElement(Element element, ElementValueComparator comparator) throws NullPointerException { TransactionContext context = getOrCreateTransactionContext(); Element previous = getCurrentElement(element.getKey(), context); if (previous != null && previous.getValue().equals(element.getValue())) { context.addCommand(new StoreRemoveElementCommand(element, comparator), element); return previous; } return null; } XATransactionalStore(Ehcache cache, EhcacheXAStore ehcacheXAStore,
TransactionManagerLookup transactionManagerLookup, TransactionManager txnManager); boolean put(final Element element); boolean putWithWriter(final Element element, final CacheWriterManager writerManager); Element get(final Object key); Element getQuiet(final Object key); final List getKeys(); Element remove(final Object key); Element removeWithWriter(final Object key, final CacheWriterManager writerManager); void removeAll(); void dispose(); int getSize(); int getOnDiskSize(); int getOffHeapSize(); int getInMemorySize(); int getTerracottaClusteredSize(); long getInMemorySizeInBytes(); long getOffHeapSizeInBytes(); long getOnDiskSizeInBytes(); Status getStatus(); boolean containsKey(final Object key); boolean containsKeyInMemory(final Object key); boolean containsKeyOffHeap(final Object key); boolean containsKeyOnDisk(final Object key); void expireElements(); void flush(); boolean bufferFull(); Policy getInMemoryEvictionPolicy(); void setInMemoryEvictionPolicy(final Policy policy); Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); Element putIfAbsent(Element element); Element removeElement(Element element, ElementValueComparator comparator); boolean replace(Element old, Element element, ElementValueComparator comparator); Element replace(Element element); EhcacheXAResource getOrCreateXAResource(); Object getMBean(); }### Answer:
@Test public void testRemoveElement() throws Exception { transactionManager.begin(); assertEquals("Cache should be empty to start", 0, cache.getSize()); assertEquals("Cach1 should be empty to start", 0, cach1.getSize()); assertFalse(cache.removeElement(new Element("blah", "someValue"))); cache.put(new Element("blah", "value")); assertFalse(cache.removeElement(new Element("blah", "someValue"))); transactionManager.commit(); transactionManager.begin(); assertNotNull(cache.get("blah")); assertTrue(cache.removeElement(new Element("blah", "value"))); transactionManager.commit(); transactionManager.begin(); assertNull(cache.get("blah")); transactionManager.commit(); transactionManager.begin(); cache.put(new Element("key", "value")); transactionManager.commit(); transactionManager.begin(); cach1.put(new Element("random", "things")); cache.removeElement(new Element("key", "value")); Transaction tx1 = transactionManager.suspend(); transactionManager.begin(); assertTrue(cache.removeElement(new Element("key", "value"))); transactionManager.commit(); transactionManager.resume(tx1); try { transactionManager.commit(); fail("Transaction should have failed, element is deleted already"); } catch (RollbackException e) { } transactionManager.begin(); assertNull(cache.get("key")); transactionManager.commit(); transactionManager.begin(); cache.put(new Element("key", "value")); transactionManager.commit(); transactionManager.begin(); cach1.put(new Element("random", "things")); cache.removeElement(new Element("key", "value")); tx1 = transactionManager.suspend(); transactionManager.begin(); cache.put(new Element("key", "newValue")); transactionManager.commit(); transactionManager.resume(tx1); try { transactionManager.commit(); fail("Transaction should have failed, element has changed in the meantime!"); } catch (RollbackException e) { } transactionManager.begin(); assertNotNull(cache.get("key")); assertEquals("newValue", cache.get("key").getValue()); transactionManager.commit(); } |
### Question:
CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { LOG.debug("CacheManager already shutdown"); return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } if (cacheManagerTimer != null) { cacheManagerTimer.cancel(); cacheManagerTimer.purge(); } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); for (Ehcache cache : ehcaches.values()) { if (cache != null) { cache.dispose(); } } defaultCache.dispose(); status = Status.STATUS_SHUTDOWN; if (this == singleton) { singleton = null; } if (terracottaClusteredInstanceFactory != null) { terracottaClusteredInstanceFactory.shutdown(); } removeShutdownHook(); } } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource( "/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } int endingThreadCount; int tries = 0; do { Thread.sleep(500); endingThreadCount = countThreads(); } while (tries++ < 5 || endingThreadCount >= startingThreadCount + 2); assertTrue(endingThreadCount < startingThreadCount + 2); }
@Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); } |
### Question:
CacheManager { public void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testRemoveCache() throws CacheException { singletonManager = CacheManager.create(); Ehcache cache = singletonManager.getCache("sampleCache1"); assertNotNull(cache); singletonManager.removeCache("sampleCache1"); cache = singletonManager.getCache("sampleCache1"); assertNull(cache); singletonManager.removeCache(null); singletonManager.removeCache(""); } |
### Question:
BlockingCache implements Ehcache { protected Ehcache getCache() { return cache; } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); @Override Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); LiveCacheStatistics getLiveCacheStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); WriteBehind getWriteBehind(); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); int getSizeBasedOnAccuracy(int statisticsAccuracy); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); void registerCacheUsageListener(CacheUsageListener cacheUsageListener); void removeCacheUsageListener(CacheUsageListener cacheUsageListener); boolean isStatisticsEnabled(); void setStatisticsEnabled(boolean enabledStatistics); SampledCacheStatistics getSampledCacheStatistics(); void setSampledStatisticsEnabled(boolean enabledStatistics); boolean isSampledStatisticsEnabled(); Object getInternalContext(); void disableDynamicFeatures(); }### Answer:
@Test public void testThrashBlockingCache() throws Exception { Ehcache cache = manager.getCache("sampleCache1"); blockingCache = new BlockingCache(cache); long duration = thrashCache(blockingCache, 50, 500L, 1000L); LOG.debug("Thrash Duration:" + duration); } |
### Question:
BlockingCache implements Ehcache { public Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument) throws CacheException { throw new CacheException("This method is not appropriate for a Blocking Cache"); } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); @Override Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); LiveCacheStatistics getLiveCacheStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); WriteBehind getWriteBehind(); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); int getSizeBasedOnAccuracy(int statisticsAccuracy); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); void registerCacheUsageListener(CacheUsageListener cacheUsageListener); void removeCacheUsageListener(CacheUsageListener cacheUsageListener); boolean isStatisticsEnabled(); void setStatisticsEnabled(boolean enabledStatistics); SampledCacheStatistics getSampledCacheStatistics(); void setSampledStatisticsEnabled(boolean enabledStatistics); boolean isSampledStatisticsEnabled(); Object getInternalContext(); void disableDynamicFeatures(); }### Answer:
@Test public void testGetWithLoader() { super.testGetWithLoader(); } |
### Question:
CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { LOG.debug("CacheManager already shutdown"); return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } if (cacheManagerTimer != null) { cacheManagerTimer.cancel(); cacheManagerTimer.purge(); } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); Collection cacheSet = ehcaches.values(); for (Iterator iterator = cacheSet.iterator(); iterator.hasNext();) { Ehcache cache = (Ehcache) iterator.next(); if (cache != null) { cache.dispose(); } } defaultCache.dispose(); status = Status.STATUS_SHUTDOWN; if (this == singleton) { singleton = null; } removeShutdownHook(); } } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(String scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource( "/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } int endingThreadCount; int tries = 0; do { Thread.sleep(500); endingThreadCount = countThreads(); } while (tries++ < 5 || endingThreadCount >= startingThreadCount + 2); assertTrue(endingThreadCount < startingThreadCount + 2); }
@Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); } |
### Question:
CacheManager { public static CacheManager create() throws CacheException { if (singleton != null) { return singleton; } synchronized (CacheManager.class) { if (singleton == null) { LOG.debug("Creating new CacheManager with default config"); singleton = new CacheManager(); } else { LOG.debug("Attempting to create an existing singleton. Existing singleton returned."); } return singleton; } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(String scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testCacheManagerThreads() throws CacheException, InterruptedException { singletonManager = CacheManager .create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml"); int threads = countThreads(); assertTrue("More than 145 threads: " + threads, countThreads() <= 145); } |
### Question:
CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); return (Cache) caches.get(name); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(String scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testGetCache() throws CacheException { instanceManager = CacheManager.create(); Ehcache cache = instanceManager.getCache("sampleCache1"); assertNotNull(cache); } |
### Question:
CacheManager { public void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = (Ehcache) ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } caches.remove(cacheName); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(String scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testRemoveCache() throws CacheException { singletonManager = CacheManager.create(); Ehcache cache = singletonManager.getCache("sampleCache1"); assertNotNull(cache); singletonManager.removeCache("sampleCache1"); cache = singletonManager.getCache("sampleCache1"); assertNull(cache); singletonManager.removeCache(null); singletonManager.removeCache(""); } |
### Question:
CacheManager { public void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache cache = null; try { cache = (Ehcache) defaultCache.clone(); } catch (CloneNotSupportedException e) { throw new CacheException("Failure adding cache. Initial cause was " + e.getMessage(), e); } if (cache != null) { cache.setName(cacheName); } addCache(cache); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(String scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCache() throws CacheException { singletonManager = CacheManager.create(); singletonManager.addCache("test"); singletonManager.addCache("test2"); Ehcache cache = singletonManager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = singletonManager.getCacheNames(); boolean match = false; for (String cacheName : cacheNames) { if (cacheName.equals("test")) { match = true; } } assertTrue(match); singletonManager.addCache(""); } |
### Question:
OnHeapCachingTier implements CachingTier<K, V> { @Override public V get(final K key, final Callable<V> source, final boolean updateStats) { if (updateStats) { getObserver.begin(); } Object cachedValue = backEnd.get(key); if (cachedValue == null) { if (updateStats) { getObserver.end(GetOutcome.MISS); } Fault<V> f = new Fault<V>(source); cachedValue = backEnd.putIfAbsent(key, f); if (cachedValue == null) { try { V value = f.get(); putObserver.begin(); if (value == null) { backEnd.remove(key, f); } else if (backEnd.replace(key, f, value)) { putObserver.end(PutOutcome.ADDED); } return value; } catch (Throwable e) { backEnd.remove(key, f); if (e instanceof RuntimeException) { throw (RuntimeException)e; } else { throw new CacheException(e); } } } } else { if (updateStats) { getObserver.end(GetOutcome.HIT); } } return getValue(cachedValue); } OnHeapCachingTier(final HeapCacheBackEnd<K, Object> backEnd); static OnHeapCachingTier<Object, Element> createOnHeapCache(final Ehcache cache, final Pool onHeapPool); @Override boolean loadOnPut(); @Override V get(final K key, final Callable<V> source, final boolean updateStats); @Override V remove(final K key); @Override void clear(); @Override void addListener(final Listener<K, V> listener); @Statistic(name = "size", tags = "local-heap") @Override int getInMemorySize(); @Override int getOffHeapSize(); @Override boolean contains(final K key); @Statistic(name = "size-in-bytes", tags = "local-heap") @Override long getInMemorySizeInBytes(); @Override long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override void recalculateSize(final K key); @Override Policy getEvictionPolicy(); @Override void setEvictionPolicy(final Policy policy); }### Answer:
@Test public void testOnlyPopulatesOnce() throws InterruptedException, BrokenBarrierException { final int threadCount = Runtime.getRuntime().availableProcessors() * 2; final CachingTier<String, String> cache = new OnHeapCachingTier<String, String>(new CountBasedBackEnd<String, Object>(threadCount * 2)); final AtomicBoolean failure = new AtomicBoolean(); final AtomicInteger invocationCounter = new AtomicInteger(); final AtomicInteger valuesRead = new AtomicInteger(); final CyclicBarrier barrier = new CyclicBarrier(threadCount + 1); final Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread() { @Override public void run() { try { final int await = barrier.await(); cache.get(KEY, new Callable<String>() { @Override public String call() throws Exception { invocationCounter.incrementAndGet(); return "0x" + Integer.toHexString(await); } }, false); valuesRead.getAndIncrement(); } catch (Exception e) { e.printStackTrace(); failure.set(true); } } }; threads[i].start(); } barrier.await(); for (Thread thread : threads) { thread.join(); } assertThat(failure.get(), is(false)); assertThat(invocationCounter.get(), is(1)); assertThat(valuesRead.get(), is(threadCount)); } |
### Question:
CountBasedBackEnd extends ConcurrentHashMap<K, V> implements HeapCacheBackEnd<K, V> { @Override public V putIfAbsent(final K key, final V value) { final V v = super.putIfAbsent(key, value); if (v == null) { try { evictIfRequired(key, value); } catch (Throwable e) { LOG.warn("Caught throwable while evicting", e); } } return v; } CountBasedBackEnd(final long maxEntriesLocalHeap); CountBasedBackEnd(final long maxEntriesLocalHeap, final Policy policy); void setPolicy(final Policy policy); @Override V putIfAbsent(final K key, final V value); @Override void registerEvictionCallback(final EvictionCallback<K, V> callback); @Override void recalculateSize(final K key); @Override Policy getPolicy(); @Override boolean hasSpace(); void setMaxEntriesLocalHeap(final long maxEntriesLocalHeap); long getMaxEntriesLocalHeap(); }### Answer:
@Test public void testEvictsWhenAtCapacityMultiThreaded() throws InterruptedException { final int limit = 1000; final int threadNumber = Runtime.getRuntime().availableProcessors() * 2; final CountBasedBackEnd<String, Element> countBasedBackEnd = new CountBasedBackEnd<String, Element>(limit); final AtomicInteger counter = new AtomicInteger(0); final Runnable runnable = new Runnable() { @Override public void run() { int i; while ((i = counter.getAndIncrement()) < limit * threadNumber * 10) { final String key = Integer.toString(i); countBasedBackEnd.putIfAbsent(key, new Element(key, i)); } } }; Thread[] threads = new Thread[threadNumber]; for (int i = 0, threadsLength = threads.length; i < threadsLength; i++) { threads[i] = new Thread(runnable); threads[i].start(); } for (Thread thread : threads) { thread.join(); } assertThat("Grew to " + countBasedBackEnd.size(), countBasedBackEnd.size() <= limit, is(true)); int size = countBasedBackEnd.size(); for (String s : countBasedBackEnd.keySet()) { assertThat(countBasedBackEnd.remove(s), notNullValue()); size--; } assertThat(size, is(0)); } |
### Question:
XATransactionalStore extends AbstractStore { public Element removeElement(Element element) throws NullPointerException { TransactionContext context = getOrCreateTransactionContext(); Element previous = getCurrentElement(element.getKey(), context); if (previous != null && previous.getValue().equals(element.getValue())) { context.addCommand(new StoreRemoveElementCommand(element), element); return previous; } return null; } XATransactionalStore(Ehcache cache, EhcacheXAStore ehcacheXAStore,
TransactionManagerLookup transactionManagerLookup, TransactionManager txnManager); boolean put(final Element element); boolean putWithWriter(final Element element, final CacheWriterManager writerManager); Element get(final Object key); Element getQuiet(final Object key); final List getKeys(); Element remove(final Object key); Element removeWithWriter(final Object key, final CacheWriterManager writerManager); void removeAll(); void dispose(); int getSize(); int getOnDiskSize(); int getOffHeapSize(); int getInMemorySize(); int getTerracottaClusteredSize(); long getInMemorySizeInBytes(); long getOffHeapSizeInBytes(); long getOnDiskSizeInBytes(); Status getStatus(); boolean containsKey(final Object key); boolean containsKeyInMemory(final Object key); boolean containsKeyOffHeap(final Object key); boolean containsKeyOnDisk(final Object key); void expireElements(); void flush(); boolean bufferFull(); Policy getInMemoryEvictionPolicy(); void setInMemoryEvictionPolicy(final Policy policy); Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); Element putIfAbsent(Element element); Element removeElement(Element element); boolean replace(Element old, Element element); boolean replace(Element old, Element element, ElementComparer comparer); Element replace(Element element); EhcacheXAResource getOrCreateXAResource(); Object getMBean(); }### Answer:
@Test public void testRemoveElement() throws Exception { transactionManager.begin(); assertEquals("Cache should be empty to start", 0, cache.getSize()); assertEquals("Cach1 should be empty to start", 0, cach1.getSize()); assertFalse(cache.removeElement(new Element("blah", "someValue"))); cache.put(new Element("blah", "value")); assertFalse(cache.removeElement(new Element("blah", "someValue"))); transactionManager.commit(); transactionManager.begin(); assertNotNull(cache.get("blah")); assertTrue(cache.removeElement(new Element("blah", "value"))); transactionManager.commit(); transactionManager.begin(); assertNull(cache.get("blah")); transactionManager.commit(); transactionManager.begin(); cache.put(new Element("key", "value")); transactionManager.commit(); transactionManager.begin(); cach1.put(new Element("random", "things")); cache.removeElement(new Element("key", "value")); Transaction tx1 = transactionManager.suspend(); transactionManager.begin(); assertTrue(cache.removeElement(new Element("key", "value"))); transactionManager.commit(); transactionManager.resume(tx1); try { transactionManager.commit(); fail("Transaction should have failed, element is deleted already"); } catch (RollbackException e) { } transactionManager.begin(); assertNull(cache.get("key")); transactionManager.commit(); transactionManager.begin(); cache.put(new Element("key", "value")); transactionManager.commit(); transactionManager.begin(); cach1.put(new Element("random", "things")); cache.removeElement(new Element("key", "value")); tx1 = transactionManager.suspend(); transactionManager.begin(); cache.put(new Element("key", "newValue")); transactionManager.commit(); transactionManager.resume(tx1); try { transactionManager.commit(); fail("Transaction should have failed, element has changed in the meantime!"); } catch (RollbackException e) { } transactionManager.begin(); assertNotNull(cache.get("key")); assertEquals("newValue", cache.get("key").getValue()); transactionManager.commit(); } |
### Question:
JCache implements net.sf.jsr107cache.Cache { public boolean isEmpty() { return (size() == 0); } JCache(Ehcache cache); JCache(Ehcache cache, net.sf.jsr107cache.CacheLoader cacheLoader); JCache(Ehcache cache, JCacheLoader cacheLoader); void setCacheLoader(JCacheLoader cacheLoader); void addListener(CacheListener cacheListener); void evict(); Map getAll(Collection keys); Map getAll(Collection keys, Object loaderArgument); CacheLoader getCacheLoader(); CacheEntry getCacheEntry(Object key); CacheStatistics getCacheStatistics(); void load(final Object key); void loadAll(final Collection keys); void loadAll(final Collection keys, final Object loaderArgument); Object peek(Object key); void removeListener(CacheListener cacheListener); int size(); boolean isEmpty(); boolean containsKey(Object key); boolean containsValue(Object value); Object get(Object key); Object get(Object key, Object loaderArgument); Object get(Object key, JCacheLoader loader); Object get(Object key, JCacheLoader loader, Object loaderArgument); Object put(Object key, Object value); Object put(Object key, Object value, int timeToLiveSeconds); Object remove(Object key); void putAll(Map sourceMap); void clear(); Set keySet(); Collection values(); Set entrySet(); void setStatisticsAccuracy(int statisticsAccuracy); Ehcache getBackingCache(); String toString(); }### Answer:
@Test public void testIsEmpty() throws Exception { Ehcache ehcache = new net.sf.ehcache.Cache("testIsEmpty", 1, true, false, 500, 200); manager.addCache(ehcache); Cache cache = new JCache(ehcache); assertTrue(cache.isEmpty()); cache.put("key1", "value1"); assertFalse(cache.isEmpty()); cache.put("key2", "value1"); assertFalse(cache.isEmpty()); assertNotNull(cache.get("key1")); assertNotNull(cache.get("key2")); }
@Test public void testIsEmpty() throws Exception { Ehcache ehcache = new net.sf.ehcache.Cache("testIsEmpty", 1, true, true, 500, 200); manager.addCache(ehcache); Cache cache = new JCache(ehcache); assertTrue(cache.isEmpty()); cache.put("key1", "value1"); assertFalse(cache.isEmpty()); cache.put("key2", "value1"); assertFalse(cache.isEmpty()); assertNotNull(cache.get("key1")); assertNotNull(cache.get("key2")); } |
### Question:
JCache implements net.sf.jsr107cache.Cache { public boolean containsKey(Object key) { return cache.isKeyInCache(key); } JCache(Ehcache cache); JCache(Ehcache cache, net.sf.jsr107cache.CacheLoader cacheLoader); JCache(Ehcache cache, JCacheLoader cacheLoader); void setCacheLoader(JCacheLoader cacheLoader); void addListener(CacheListener cacheListener); void evict(); Map getAll(Collection keys); Map getAll(Collection keys, Object loaderArgument); CacheLoader getCacheLoader(); CacheEntry getCacheEntry(Object key); CacheStatistics getCacheStatistics(); void load(final Object key); void loadAll(final Collection keys); void loadAll(final Collection keys, final Object loaderArgument); Object peek(Object key); void removeListener(CacheListener cacheListener); int size(); boolean isEmpty(); boolean containsKey(Object key); boolean containsValue(Object value); Object get(Object key); Object get(Object key, Object loaderArgument); Object get(Object key, JCacheLoader loader); Object get(Object key, JCacheLoader loader, Object loaderArgument); Object put(Object key, Object value); Object put(Object key, Object value, int timeToLiveSeconds); Object remove(Object key); void putAll(Map sourceMap); void clear(); Set keySet(); Collection values(); Set entrySet(); void setStatisticsAccuracy(int statisticsAccuracy); Ehcache getBackingCache(); String toString(); }### Answer:
@Test public void testContainsKey() throws Exception { Ehcache ehcache = new net.sf.ehcache.Cache("testContainsKey", 1, true, false, 500, 200); manager.addCache(ehcache); Cache cache = new JCache(ehcache); assertFalse(cache.containsKey("key1")); assertFalse(cache.containsKey("key2")); cache.put("key1", "value1"); assertTrue(cache.containsKey("key1")); assertFalse(cache.containsKey("key2")); cache.put("key2", "value1"); assertTrue(cache.containsKey("key1")); assertTrue(cache.containsKey("key2")); assertNotNull(cache.get("key1")); assertNotNull(cache.get("key2")); }
@Test public void testContainsKey() throws Exception { Ehcache ehcache = new net.sf.ehcache.Cache("testContainsKey", 1, true, true, 500, 200); manager.addCache(ehcache); Cache cache = new JCache(ehcache); assertFalse(cache.containsKey("key1")); assertFalse(cache.containsKey("key2")); cache.put("key1", "value1"); assertTrue(cache.containsKey("key1")); assertFalse(cache.containsKey("key2")); cache.put("key2", "value1"); assertTrue(cache.containsKey("key1")); assertTrue(cache.containsKey("key2")); assertNotNull(cache.get("key1")); assertNotNull(cache.get("key2")); } |
### Question:
JCache implements net.sf.jsr107cache.Cache { public boolean containsValue(Object value) { long start = System.currentTimeMillis(); boolean inCache = cache.isValueInCache(value); long end = System.currentTimeMillis(); if (LOG.isWarnEnabled()) { LOG.warn("Performance Warning: containsValue is not recommended. This call took " + (end - start) + " ms"); } return inCache; } JCache(Ehcache cache); JCache(Ehcache cache, net.sf.jsr107cache.CacheLoader cacheLoader); JCache(Ehcache cache, JCacheLoader cacheLoader); void setCacheLoader(JCacheLoader cacheLoader); void addListener(CacheListener cacheListener); void evict(); Map getAll(Collection keys); Map getAll(Collection keys, Object loaderArgument); CacheLoader getCacheLoader(); CacheEntry getCacheEntry(Object key); CacheStatistics getCacheStatistics(); void load(final Object key); void loadAll(final Collection keys); void loadAll(final Collection keys, final Object loaderArgument); Object peek(Object key); void removeListener(CacheListener cacheListener); int size(); boolean isEmpty(); boolean containsKey(Object key); boolean containsValue(Object value); Object get(Object key); Object get(Object key, Object loaderArgument); Object get(Object key, JCacheLoader loader); Object get(Object key, JCacheLoader loader, Object loaderArgument); Object put(Object key, Object value); Object put(Object key, Object value, int timeToLiveSeconds); Object remove(Object key); void putAll(Map sourceMap); void clear(); Set keySet(); Collection values(); Set entrySet(); void setStatisticsAccuracy(int statisticsAccuracy); Ehcache getBackingCache(); String toString(); }### Answer:
@Test public void testContainsValue() throws Exception { Ehcache ehcache = new net.sf.ehcache.Cache("testContainsValue", 2, true, false, 500, 200); manager.addCache(ehcache); Cache cache = new JCache(ehcache); assertFalse(cache.containsValue("value1")); assertFalse(cache.containsValue(null)); cache.put("key1", null); assertFalse(cache.containsValue("value1")); assertTrue(cache.containsValue(null)); cache.put("key2", "value1"); assertTrue(cache.containsValue("value1")); assertTrue(cache.containsValue(null)); assertNull(cache.get("key1")); assertNotNull(cache.get("key2")); }
@Test public void testContainsValue() throws Exception { Ehcache ehcache = new net.sf.ehcache.Cache("testContainsValue", 2, true, true, 500, 200); manager.addCache(ehcache); Cache cache = new JCache(ehcache); assertFalse(cache.containsValue("value1")); assertFalse(cache.containsValue(null)); cache.put("key1", null); assertFalse(cache.containsValue("value1")); assertTrue(cache.containsValue(null)); cache.put("key2", "value1"); assertTrue(cache.containsValue("value1")); assertTrue(cache.containsValue(null)); assertNull(cache.get("key1")); assertNotNull(cache.get("key2")); } |
### Question:
JCache implements net.sf.jsr107cache.Cache { public void putAll(Map sourceMap) { if (sourceMap == null) { return; } for (Iterator iterator = sourceMap.keySet().iterator(); iterator.hasNext();) { Object key = iterator.next(); cache.put(new Element(key, sourceMap.get(key))); } } JCache(Ehcache cache); JCache(Ehcache cache, net.sf.jsr107cache.CacheLoader cacheLoader); JCache(Ehcache cache, JCacheLoader cacheLoader); void setCacheLoader(JCacheLoader cacheLoader); void addListener(CacheListener cacheListener); void evict(); Map getAll(Collection keys); Map getAll(Collection keys, Object loaderArgument); CacheLoader getCacheLoader(); CacheEntry getCacheEntry(Object key); CacheStatistics getCacheStatistics(); void load(final Object key); void loadAll(final Collection keys); void loadAll(final Collection keys, final Object loaderArgument); Object peek(Object key); void removeListener(CacheListener cacheListener); int size(); boolean isEmpty(); boolean containsKey(Object key); boolean containsValue(Object value); Object get(Object key); Object get(Object key, Object loaderArgument); Object get(Object key, JCacheLoader loader); Object get(Object key, JCacheLoader loader, Object loaderArgument); Object put(Object key, Object value); Object put(Object key, Object value, int timeToLiveSeconds); Object remove(Object key); void putAll(Map sourceMap); void clear(); Set keySet(); Collection values(); Set entrySet(); void setStatisticsAccuracy(int statisticsAccuracy); Ehcache getBackingCache(); String toString(); }### Answer:
@Test public void testPutAll() { Ehcache ehcache = new net.sf.ehcache.Cache("testPutAll", 2, true, false, 500, 200); manager.addCache(ehcache); Cache cache = new JCache(ehcache); assertTrue(cache.isEmpty()); cache.putAll(null); assertTrue(cache.isEmpty()); cache.putAll(new HashMap()); assertTrue(cache.isEmpty()); Map map = new HashMap(); for (int i = 0; i < 10; i++) { map.put(i + "", new Date()); } cache.putAll(map); assertEquals(10, cache.size()); }
@Test public void testPutAll() { Ehcache ehcache = new net.sf.ehcache.Cache("testPutAll", 2, true, true, 500, 200); manager.addCache(ehcache); Cache cache = new JCache(ehcache); assertTrue(cache.isEmpty()); cache.putAll(null); assertTrue(cache.isEmpty()); cache.putAll(new HashMap()); assertTrue(cache.isEmpty()); Map map = new HashMap(); for (int i = 0; i < 10; i++) { map.put(i + "", new Date()); } cache.putAll(map); assertEquals(10, cache.size()); } |
### Question:
JCache implements net.sf.jsr107cache.Cache { public void clear() { cache.removeAll(); } JCache(Ehcache cache); JCache(Ehcache cache, net.sf.jsr107cache.CacheLoader cacheLoader); JCache(Ehcache cache, JCacheLoader cacheLoader); void setCacheLoader(JCacheLoader cacheLoader); void addListener(CacheListener cacheListener); void evict(); Map getAll(Collection keys); Map getAll(Collection keys, Object loaderArgument); CacheLoader getCacheLoader(); CacheEntry getCacheEntry(Object key); CacheStatistics getCacheStatistics(); void load(final Object key); void loadAll(final Collection keys); void loadAll(final Collection keys, final Object loaderArgument); Object peek(Object key); void removeListener(CacheListener cacheListener); int size(); boolean isEmpty(); boolean containsKey(Object key); boolean containsValue(Object value); Object get(Object key); Object get(Object key, Object loaderArgument); Object get(Object key, JCacheLoader loader); Object get(Object key, JCacheLoader loader, Object loaderArgument); Object put(Object key, Object value); Object put(Object key, Object value, int timeToLiveSeconds); Object remove(Object key); void putAll(Map sourceMap); void clear(); Set keySet(); Collection values(); Set entrySet(); void setStatisticsAccuracy(int statisticsAccuracy); Ehcache getBackingCache(); String toString(); }### Answer:
@Test public void testClear() { Ehcache ehcache = new net.sf.ehcache.Cache("testClear", 2, true, false, 500, 200); manager.addCache(ehcache); Cache cache = new JCache(ehcache); assertTrue(cache.isEmpty()); cache.clear(); assertTrue(cache.isEmpty()); cache.put("1", new Date()); cache.clear(); assertTrue(cache.isEmpty()); }
@Test public void testClear() { Ehcache ehcache = new net.sf.ehcache.Cache("testClear", 2, true, true, 500, 200); manager.addCache(ehcache); Cache cache = new JCache(ehcache); assertTrue(cache.isEmpty()); cache.clear(); assertTrue(cache.isEmpty()); cache.put("1", new Date()); cache.clear(); assertTrue(cache.isEmpty()); } |
### Question:
JCache implements net.sf.jsr107cache.Cache { public Set keySet() { List list = cache.getKeys(); Set set = new HashSet(); set.addAll(list); return set; } JCache(Ehcache cache); JCache(Ehcache cache, net.sf.jsr107cache.CacheLoader cacheLoader); JCache(Ehcache cache, JCacheLoader cacheLoader); void setCacheLoader(JCacheLoader cacheLoader); void addListener(CacheListener cacheListener); void evict(); Map getAll(Collection keys); Map getAll(Collection keys, Object loaderArgument); CacheLoader getCacheLoader(); CacheEntry getCacheEntry(Object key); CacheStatistics getCacheStatistics(); void load(final Object key); void loadAll(final Collection keys); void loadAll(final Collection keys, final Object loaderArgument); Object peek(Object key); void removeListener(CacheListener cacheListener); int size(); boolean isEmpty(); boolean containsKey(Object key); boolean containsValue(Object value); Object get(Object key); Object get(Object key, Object loaderArgument); Object get(Object key, JCacheLoader loader); Object get(Object key, JCacheLoader loader, Object loaderArgument); Object put(Object key, Object value); Object put(Object key, Object value, int timeToLiveSeconds); Object remove(Object key); void putAll(Map sourceMap); void clear(); Set keySet(); Collection values(); Set entrySet(); void setStatisticsAccuracy(int statisticsAccuracy); Ehcache getBackingCache(); String toString(); }### Answer:
@Test public void testKeySet() { Ehcache ehcache = new net.sf.ehcache.Cache("testKeySet", 2, true, false, 500, 200); manager.addCache(ehcache); Cache cache = new JCache(ehcache); for (int i = 0; i < 10; i++) { cache.put(i + "", new Date()); } cache.put(0 + "", new Date()); Set set = cache.keySet(); assertEquals(10, set.size()); }
@Test public void testKeySet() { Ehcache ehcache = new net.sf.ehcache.Cache("testKeySet", 2, true, true, 500, 200); manager.addCache(ehcache); Cache cache = new JCache(ehcache); for (int i = 0; i < 10; i++) { cache.put(i + "", new Date()); } cache.put(0 + "", new Date()); Set set = cache.keySet(); assertEquals(10, set.size()); } |
### Question:
JCacheStatistics implements CacheStatistics, Serializable { public void clearStatistics() { statistics.clearStatistics(); } JCacheStatistics(Statistics statistics); int getStatisticsAccuracy(); void clearStatistics(); int getCacheHits(); int getCacheMisses(); int getObjectCount(); float getAverageGetTime(); long getEvictionCount(); }### Answer:
@Test public void testClearStatistics() throws InterruptedException { Ehcache ehcache = new net.sf.ehcache.Cache("test", 1, true, false, 5, 2); manager.addCache(ehcache); ehcache.setStatisticsEnabled(true); Cache cache = new JCache(ehcache, null); cache.put("key1", "value1"); cache.put("key2", "value1"); cache.get("key1"); CacheStatistics statistics = cache.getCacheStatistics(); assertEquals(1, statistics.getCacheHits()); assertEquals(0, statistics.getCacheMisses()); statistics.clearStatistics(); statistics = cache.getCacheStatistics(); assertEquals(0, statistics.getCacheHits()); assertEquals(0, statistics.getCacheMisses()); }
@Test public void testClearStatistics() throws InterruptedException { Ehcache ehcache = new net.sf.ehcache.Cache("test", 1, true, false, 5, 2); manager.addCache(ehcache); Cache cache = new JCache(ehcache, null); cache.put("key1", "value1"); cache.put("key2", "value1"); cache.get("key1"); CacheStatistics statistics = cache.getCacheStatistics(); assertEquals(1, statistics.getCacheHits()); assertEquals(0, statistics.getCacheMisses()); statistics.clearStatistics(); statistics = cache.getCacheStatistics(); assertEquals(0, statistics.getCacheHits()); assertEquals(0, statistics.getCacheMisses()); } |
### Question:
SummedSampledCounter extends DerivedSampledCounterImpl { @Override public long getValue() { long l = 0; for (SampledCounter sc : delegates) { l = l + sc.getValue(); } return l; } SummedSampledCounter(SampledCounterConfig config, SampledCounter... delegates); @Override long getValue(); }### Answer:
@Test public void testSummed() { SampledCounterConfig configSec = new SampledCounterConfig(1, 10, true, 0); SampledCounterImpl counter1 = new SampledCounterImpl(configSec); SampledCounterImpl counter2 = new SampledCounterImpl(configSec); SampledCounterImpl counter3 = new SampledCounterImpl(configSec); SummedSampledCounter summedCounter = new SummedSampledCounter(configSec, counter1, counter2, counter3); counter1.setValue(0); counter2.setValue(0); counter3.setValue(0); Assert.assertEquals(0, summedCounter.getValue()); counter1.setValue(10); Assert.assertEquals(10, summedCounter.getValue()); summedCounter.setValue(-10); Assert.assertEquals(10, summedCounter.getValue()); Assert.assertEquals(10, summedCounter.getAndReset()); Assert.assertEquals(10, summedCounter.getValue()); counter2.setValue(20); counter3.setValue(30); summedCounter.recordSample(); counter1.getAndReset(); counter2.getAndReset(); counter3.getAndReset(); summedCounter.recordSample(); System.out.println("summed"); for (TimeStampedCounterValue tscv : summedCounter.getAllSampleValues()) { System.out.println("\t" + tscv); } Assert.assertEquals(0, summedCounter.getMostRecentSample().getCounterValue()); Assert.assertEquals(0, summedCounter.getAllSampleValues()[0].getCounterValue()); Assert.assertEquals(60, summedCounter.getAllSampleValues()[1].getCounterValue()); Assert.assertEquals(0, summedCounter.getAllSampleValues()[2].getCounterValue()); }
@Test public void testNoops() { SampledCounterConfig configSec = new SampledCounterConfig(1, 10, true, 0); SampledCounterImpl counter1 = new SampledCounterImpl(configSec); SampledCounterImpl counter2 = new SampledCounterImpl(configSec); SampledCounterImpl counter3 = new SampledCounterImpl(configSec); SummedSampledCounter summedCounter = new SummedSampledCounter(configSec, counter1, counter2, counter3); counter1.setValue(10); counter2.setValue(10); counter3.setValue(10); summedCounter.decrement(); summedCounter.decrement(10); summedCounter.increment(); summedCounter.increment(10); summedCounter.setValue(100); summedCounter.getAndReset(); Assert.assertEquals(30, summedCounter.getValue()); } |
### Question:
SelfPopulatingCache extends BlockingCache { public void refresh() throws CacheException { Exception exception = null; Object keyWithException = null; final Collection keys = getKeys(); if (LOG.isLoggable(Level.FINEST)) { LOG.finest(getName() + ": found " + keys.size() + " keys to refresh"); } for (Iterator iterator = keys.iterator(); iterator.hasNext();) { final Object key = iterator.next(); try { Ehcache backingCache = getCache(); final Element element = backingCache.getQuiet(key); if (element == null) { if (LOG.isLoggable(Level.FINEST)) { LOG.finest(getName() + ": entry with key " + key + " has been removed - skipping it"); } continue; } refreshElement(element, backingCache); } catch (final Exception e) { LOG.log(Level.WARNING, getName() + "Could not refresh element " + key, e); exception = e; } } if (exception != null) { throw new CacheException(exception.getMessage() + " on refresh with key " + keyWithException); } } SelfPopulatingCache(final Ehcache cache, final CacheEntryFactory factory); Element get(final Object key); void refresh(); }### Answer:
@Test public void testRefresh() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new SelfPopulatingCache(cache, factory); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(1, factory.getCount()); selfPopulatingCache.refresh(); assertEquals(2, factory.getCount()); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(2, factory.getCount()); } |
### Question:
BlockingCache implements Ehcache { protected Ehcache getCache() { return cache; } BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); String getMasterGroupKey(); void setMasterGroupKey(String masterGroupKey); Set removeByGroup(Object groupKey, boolean doNotNotifyCacheReplicators); Set getKeysForGroup(Object groupKey); }### Answer:
@Test public void testThrashBlockingCache() throws Exception { Ehcache cache = manager.getCache("sampleCache1"); blockingCache = new BlockingCache(cache); long duration = thrashCache(blockingCache, 50, 500L, 1000L); LOG.fine("Thrash Duration:" + duration); } |
### Question:
BlockingCache implements Ehcache { public Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument) throws CacheException { throw new CacheException("This method is not appropriate for a Blocking Cache"); } BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); String getMasterGroupKey(); void setMasterGroupKey(String masterGroupKey); Set removeByGroup(Object groupKey, boolean doNotNotifyCacheReplicators); Set getKeysForGroup(Object groupKey); }### Answer:
@Test public void testGetWithLoader() { super.testGetWithLoader(); } |
### Question:
GroupElement extends Element { public Set getMemberKeys() { return (Set) getObjectValue(); } GroupElement(Object key); GroupElement(Object key, Object value, long version,
long creationTime, long lastAccessTime, long nextToLastAccessTime,
long lastUpdateTime, long hitCount); Set getMemberKeys(); static final String MASTER_GROUP_KEY; }### Answer:
@Test public void testConstructor() { GroupElement element = new GroupElement("key"); assertEquals("key", element.getKey()); assertNotNull(element.getObjectValue()); assertTrue(element.getObjectValue() instanceof Set); assertEquals(0, ((Set) element.getValue()).size()); assertNotNull(element.getMemberKeys()); assertEquals(0, element.getMemberKeys().size()); assertEquals(0L, element.getVersion()); long now = System.currentTimeMillis(); long MARGIN = 2000L; assertTrue(element.getCreationTime()-now<MARGIN); assertEquals(0L, element.getLastAccessTime()); assertEquals(0L, element.getNextToLastAccessTime()); assertEquals(0L, element.getLastUpdateTime()); assertEquals(0L, element.getHitCount()); } |
### Question:
CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("CacheManager already shutdown"); } return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); Collection cacheSet = ehcaches.values(); for (Iterator iterator = cacheSet.iterator(); iterator.hasNext();) { Ehcache cache = (Ehcache) iterator.next(); if (cache != null) { cache.dispose(); } } defaultCache.dispose(); status = Status.STATUS_SHUTDOWN; if (this == singleton) { singleton = null; } removeShutdownHook(); } } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); void setName(String name); String toString(); String getDiskStorePath(); static final List ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource("/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } Thread.sleep(300); int endingThreadCount = countThreads(); assertTrue(endingThreadCount < startingThreadCount + 2); }
@Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); } |
### Question:
CacheManager { public static CacheManager create() throws CacheException { if (singleton != null) { return singleton; } synchronized (CacheManager.class) { if (singleton == null) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Creating new CacheManager with default config"); } singleton = new CacheManager(); } else { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Attempting to create an existing singleton. Existing singleton returned."); } } return singleton; } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); void setName(String name); String toString(); String getDiskStorePath(); static final List ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testCacheManagerThreads() throws CacheException, InterruptedException { singletonManager = CacheManager.create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml"); int threads = countThreads(); assertTrue("More than 75 threads: " + threads, countThreads() <= 75); } |
### Question:
Element implements Serializable, Cloneable { public final long getSerializedSize() { if (!isSerializable()) { return 0; } long size = 0; ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(bout); oos.writeObject(this); size = bout.size(); return size; } catch (IOException e) { LOG.fine("Error measuring element size for element with key " + key + ". Cause was: " + e.getMessage()); } finally { try { if (oos != null) { oos.close(); } } catch (Exception e) { LOG.severe("Error closing ObjectOutputStream"); } } return size; } Element(Serializable key, Serializable value, long version); Element(Object key, Object value, long version); Element(Object key, Object value, long version,
long creationTime, long lastAccessTime,
long nextToLastAccessTime, long lastUpdateTime,
long hitCount); Element(Object key, Object value,
Boolean eternal, Integer timeToIdleSeconds, Integer timeToLiveSeconds); Element(Serializable key, Serializable value); Element(Object key, Object value); final Serializable getKey(); final Object getObjectKey(); final Serializable getValue(); final Object getObjectValue(); final boolean equals(Object object); void setTimeToLive(int timeToLiveSeconds); void setTimeToIdle(int timeToIdleSeconds); final int hashCode(); final void setVersion(long version); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final void setCreateTime(); final long getVersion(); final long getLastAccessTime(); final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); final String toString(); final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); long getExpirationTime(); boolean isEternal(); void setEternal(boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); Set getGroupKeys(); void setGroupKeys(Set groupKeys); boolean hasGroupKeys(); boolean addGroupKey(Object groupKey); boolean removeGroupKey(Object groupKey); }### Answer:
@Test public void testSerializationPerformanceByteArray() throws CacheException { Serializable key = "key"; ByteArrayOutputStream bout = new ByteArrayOutputStream(); for (int j = 0; j < 10000; j++) { try { bout.write("abcdefghijklmnopqrstv1234567890".getBytes()); } catch (IOException e) { LOG.severe("This should not happen"); } } byte[] value = bout.toByteArray(); Element element = new Element(key, value); StopWatch stopWatch = new StopWatch(); for (int i = 0; i < 100; i++) { element.getSerializedSize(); } long elapsed = stopWatch.getElapsedTime() / 100; LOG.info("In-memory size in bytes: " + element.getSerializedSize() + " time to serialize in ms: " + elapsed); assertTrue("Large object clone takes more than than 100ms", elapsed < 100); }
@Test public void testSerializationPerformanceJavaObjects() throws Exception { HashMap map = new HashMap(10000); for (int j = 0; j < 10000; j++) { map.put("key" + j, new String[]{"adfdafs", "asdfdsafa", "sdfasdf"}); } Element element = new Element("key1", map); StopWatch stopWatch = new StopWatch(); for (int i = 0; i < 100; i++) { element.getSerializedSize(); } long elapsed = stopWatch.getElapsedTime() / 100; LOG.info("In-memory size in bytes: " + element.getSerializedSize() + " time to serialize in ms: " + elapsed); assertTrue("Large object clone took more than 500ms", elapsed < 500); } |
### Question:
Element implements Serializable, Cloneable { public final boolean isSerializable() { return isKeySerializable() && (value instanceof Serializable || value == null); } Element(Serializable key, Serializable value, long version); Element(Object key, Object value, long version); Element(Object key, Object value, long version,
long creationTime, long lastAccessTime,
long nextToLastAccessTime, long lastUpdateTime,
long hitCount); Element(Object key, Object value,
Boolean eternal, Integer timeToIdleSeconds, Integer timeToLiveSeconds); Element(Serializable key, Serializable value); Element(Object key, Object value); final Serializable getKey(); final Object getObjectKey(); final Serializable getValue(); final Object getObjectValue(); final boolean equals(Object object); void setTimeToLive(int timeToLiveSeconds); void setTimeToIdle(int timeToIdleSeconds); final int hashCode(); final void setVersion(long version); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final void setCreateTime(); final long getVersion(); final long getLastAccessTime(); final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); final String toString(); final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); long getExpirationTime(); boolean isEternal(); void setEternal(boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); Set getGroupKeys(); void setGroupKeys(Set groupKeys); boolean hasGroupKeys(); boolean addGroupKey(Object groupKey); boolean removeGroupKey(Object groupKey); }### Answer:
@Test public void testIsSerializable() { Element element = new Element(null, null); assertTrue(element.isSerializable()); Element elementWithNullValue = new Element("1", null); assertTrue(elementWithNullValue.isSerializable()); Element elementWithNullKey = new Element(null, "1"); assertTrue(elementWithNullValue.isSerializable()); Element elementWithObjectKey = new Element(new Object(), "1"); assertTrue(elementWithNullValue.isSerializable()); } |
### Question:
Element implements Serializable, Cloneable { public final boolean equals(Object object) { if (object == null || !(object instanceof Element)) { return false; } Element element = (Element) object; if (key == null || element.getObjectKey() == null) { return false; } return key.equals(element.getObjectKey()); } Element(Serializable key, Serializable value, long version); Element(Object key, Object value, long version); Element(Object key, Object value, long version,
long creationTime, long lastAccessTime,
long nextToLastAccessTime, long lastUpdateTime,
long hitCount); Element(Object key, Object value,
Boolean eternal, Integer timeToIdleSeconds, Integer timeToLiveSeconds); Element(Serializable key, Serializable value); Element(Object key, Object value); final Serializable getKey(); final Object getObjectKey(); final Serializable getValue(); final Object getObjectValue(); final boolean equals(Object object); void setTimeToLive(int timeToLiveSeconds); void setTimeToIdle(int timeToIdleSeconds); final int hashCode(); final void setVersion(long version); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final void setCreateTime(); final long getVersion(); final long getLastAccessTime(); final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); final String toString(); final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); long getExpirationTime(); boolean isEternal(); void setEternal(boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); Set getGroupKeys(); void setGroupKeys(Set groupKeys); boolean hasGroupKeys(); boolean addGroupKey(Object groupKey); boolean removeGroupKey(Object groupKey); }### Answer:
@Test public void testEquals() { Element element = new Element("key", "value"); assertFalse(element.equals("dog")); assertTrue(element.equals(element)); assertFalse(element.equals(null)); assertFalse(element.equals(new Element("cat", "hat"))); } |
### Question:
PayloadUtil { public static byte[] gzip(byte[] ungzipped) { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try { final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bytes); gzipOutputStream.write(ungzipped); gzipOutputStream.close(); } catch (IOException e) { LOG.severe("Could not gzip " + ungzipped); } return bytes.toByteArray(); } private PayloadUtil(); static byte[] assembleUrlList(List localCachePeers); static byte[] gzip(byte[] ungzipped); static byte[] ungzip(final byte[] gzipped); static final int MTU; static final String URL_DELIMITER; }### Answer:
@Test public void testMaximumDatagram() throws IOException { String payload = createReferenceString(); final byte[] compressed = PayloadUtil.gzip(payload.getBytes()); int length = compressed.length; LOG.info("gzipped size: " + length); assertTrue("Heartbeat too big for one Datagram " + length, length <= 1500); }
@Test public void testGzipSanityAndPerformance() throws IOException, InterruptedException { String payload = createReferenceString(); for (int i = 0; i < 10; i++) { byte[] compressed = PayloadUtil.gzip(payload.getBytes()); assertTrue(compressed.length > 300); Thread.sleep(20); } int hashCode = payload.hashCode(); StopWatch stopWatch = new StopWatch(); for (int i = 0; i < 10000; i++) { if (hashCode != payload.hashCode()) { PayloadUtil.gzip(payload.getBytes()); } } long elapsed = stopWatch.getElapsedTime(); LOG.info("Gzip took " + elapsed / 10F + " µs"); } |
### Question:
CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); Ehcache ehcache = ehcaches.get(name); return ehcache instanceof Cache ? (Cache) ehcache : null; } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removeAllCaches(); @Deprecated void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); @Override String toString(); DiskStorePathManager getDiskStorePathManager(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); FeaturesManager getFeaturesManager(); void sendManagementEvent(Serializable event, String type); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testGetCache() throws CacheException { CacheManager manager = new CacheManager(new Configuration().cache(new CacheConfiguration("foo", 100))); try { assertNotNull(manager.getCache("foo")); } finally { manager.shutdown(); } } |
### Question:
ElementResource { @DELETE public void deleteElement() throws NotFoundException { LOG.log(Level.FINE, "DELETE element {0}", element); net.sf.ehcache.Cache ehcache = lookupCache(); if (element.equals("*")) { ehcache.removeAll(); } else { boolean removed = ehcache.remove(element); if (!removed) { throw new NotFoundException("Element " + element + " not found"); } } } ElementResource(UriInfo uriInfo, Request request,
String cache, String element); @HEAD Response getElementHeader(); @GET Response getElement(); @PUT Response putElement(@Context HttpHeaders headers, byte[] data); @DELETE void deleteElement(); }### Answer:
@Test public void testDeleteElement() throws Exception { long beforeCreated = System.currentTimeMillis(); Thread.sleep(10); String originalString = "The rain in Spain falls mainly on the plain"; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(originalString.getBytes()); int status = HttpUtil.put("http: assertEquals(201, status); HttpURLConnection urlConnection = HttpUtil.get("http: assertEquals(200, urlConnection.getResponseCode()); urlConnection = HttpUtil.delete("http: assertEquals(404, HttpUtil.get("http: } |
### Question:
ElementResource { @GET public Response getElement() throws NotFoundException { LOG.log(Level.FINE, "GET element {}", element); net.sf.ehcache.Cache ehcache = lookupCache(); net.sf.ehcache.Element ehcacheElement = lookupElement(ehcache); Element localElement = new Element(ehcacheElement, uriInfo.getAbsolutePath().toString()); Date lastModifiedDate = createLastModified(ehcacheElement); EntityTag entityTag = createETag(ehcacheElement); Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(lastModifiedDate, entityTag); if (responseBuilder != null) { return responseBuilder.build(); } else { return Response.ok(localElement.getValue(), localElement.getMimeType()) .lastModified(lastModifiedDate) .tag(entityTag) .header("Expires", (new Date(localElement.getExpirationDate())).toString()) .build(); } } ElementResource(UriInfo uriInfo, Request request,
String cache, String element); @HEAD Response getElementHeader(); @GET Response getElement(); @PUT Response putElement(@Context HttpHeaders headers, byte[] data); @DELETE void deleteElement(); }### Answer:
@Test public void testGetElement() throws Exception { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); assertEquals("application/xml", result.getContentType()); JAXBContext jaxbContext = new JAXBContextResolver().getContext(Caches.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Cache cache = (Cache) unmarshaller.unmarshal(result.getInputStream()); assertEquals("sampleCache1", cache.getName()); assertEquals("http: assertNotNull("http: } |
### Question:
CacheResource { @GET public Cache getCache() { LOG.log(Level.FINE, "GET Cache {}" + cache); net.sf.ehcache.Cache ehcache = MANAGER.getCache(cache); if (ehcache == null) { throw new NotFoundException("Cache not found"); } String cacheAsString = ehcache.toString(); cacheAsString = cacheAsString.substring(0, cacheAsString.length() - 1); cacheAsString = cacheAsString + "size = " + ehcache.getSize() + " ]"; return new Cache(ehcache.getName(), uriInfo.getAbsolutePath().toString(), cacheAsString, new Statistics(ehcache.getStatistics()), ehcache.getCacheConfiguration()); } CacheResource(UriInfo uriInfo, Request request, String cache); @HEAD Response getCacheHeader(); @GET Cache getCache(); @PUT Response putCache(); @DELETE Response deleteCache(); @Path(value = "{element}") ElementResource getElementResource(@PathParam("element")String element); }### Answer:
@Test public void testGetCache() throws Exception { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); assertEquals("application/xml", result.getContentType()); JAXBContext jaxbContext = new JAXBContextResolver().getContext(Caches.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Cache cache = (Cache) unmarshaller.unmarshal(result.getInputStream()); assertEquals("sampleCache1", cache.getName()); assertEquals("http: assertNotNull("http: } |
### Question:
CacheResource { @DELETE public Response deleteCache() { LOG.log(Level.FINE, "DELETE Cache {}" + cache); net.sf.ehcache.Cache ehcache = MANAGER.getCache(cache); Response response; if (ehcache == null) { throw new NotFoundException("Cache not found " + cache); } else { CacheManager.getInstance().removeCache(cache); response = Response.ok().build(); } return response; } CacheResource(UriInfo uriInfo, Request request, String cache); @HEAD Response getCacheHeader(); @GET Cache getCache(); @PUT Response putCache(); @DELETE Response deleteCache(); @Path(value = "{element}") ElementResource getElementResource(@PathParam("element")String element); }### Answer:
@Test public void testDeleteCache() throws Exception { HttpURLConnection urlConnection = HttpUtil.put("http: urlConnection = HttpUtil.delete("http: assertEquals(200, urlConnection.getResponseCode()); if (urlConnection.getHeaderField("Server").matches("(.*)Glassfish(.*)")) { assertTrue(urlConnection.getContentType().matches("text/plain(.*)")); } String responseBody = HttpUtil.inputStreamToText(urlConnection.getInputStream()); assertEquals("", responseBody); urlConnection = HttpUtil.delete("http: assertEquals(404, urlConnection.getResponseCode()); assertTrue(urlConnection.getContentType().matches("text/plain(.*)")); try { responseBody = HttpUtil.inputStreamToText(urlConnection.getInputStream()); } catch (IOException e) { } } |
### Question:
HttpDateFormatter { public synchronized Date parseDateFromHttpDate(String date) { try { return httpDateFormat.parse(date); } catch (ParseException e) { LOG.log(Level.FINE, "ParseException on date {0}. 1/1/1970 will be returned", date); return new Date(0); } } HttpDateFormatter(); synchronized String formatHttpDate(Date date); synchronized Date parseDateFromHttpDate(String date); }### Answer:
@Test public void testParseBadDate() { HttpDateFormatter httpDateFormatter = new HttpDateFormatter(); String dateString1 = "dddddddddd^^^3s"; Date date = httpDateFormatter.parseDateFromHttpDate(dateString1); assertEquals(new Date(0), date); } |
### Question:
AsyncWriteBehind implements WriteBehind { public void delete(CacheEntry entry) { readLock.lock(); try { status.checkRunning(); async.add(new DeleteAsyncOperation(createKeySnapshot(entry.getKey()), createElementSnapshot(entry.getElement()))); } finally { readLock.unlock(); } } AsyncWriteBehind(AsyncCoordinator async, Ehcache cache, DsoSerializationStrategy serializationStrategy); void start(CacheWriter writer); void write(Element element); void delete(CacheEntry entry); void setOperationsFilter(final OperationsFilter filter); void stop(); long getQueueSize(); }### Answer:
@Test(expected = IllegalStateException.class) public void testDeleteThrowsWhenNotStarted() { AsyncWriteBehind writeBehind = createAsyncWriteBehind(); writeBehind.delete(new CacheEntry("", new Element("", ""))); } |
### Question:
AsyncWriteBehind implements WriteBehind { public void write(Element element) { readLock.lock(); try { status.checkRunning(); ElementSnapshot snapshot = createElementSnapshot(element); async.add(new WriteAsyncOperation(snapshot)); } finally { readLock.unlock(); } } AsyncWriteBehind(AsyncCoordinator async, Ehcache cache, DsoSerializationStrategy serializationStrategy); void start(CacheWriter writer); void write(Element element); void delete(CacheEntry entry); void setOperationsFilter(final OperationsFilter filter); void stop(); long getQueueSize(); }### Answer:
@Test(expected = IllegalStateException.class) public void testWriteThrowsWhenNotStarted() { AsyncWriteBehind writeBehind = createAsyncWriteBehind(); writeBehind.write(new Element("", "")); } |
### Question:
CacheManager { public synchronized void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); runtimeCfg.removeCache(cache.getCacheConfiguration()); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removeAllCaches(); @Deprecated void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); @Override String toString(); DiskStorePathManager getDiskStorePathManager(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); FeaturesManager getFeaturesManager(); void sendManagementEvent(Serializable event, String type); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testRemoveCache() throws CacheException { Configuration config = new Configuration().cache(new CacheConfiguration("foo", 100)); CacheManager manager = new CacheManager(config); try { assertEquals(1, manager.getConfiguration().getCacheConfigurations().size()); assertNotNull(manager.getCache("foo")); manager.removeCache("foo"); assertNull(manager.getCache("foo")); assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); manager.removeCache(null); manager.removeCache(""); assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); } finally { manager.shutdown(); } } |
### Question:
CacheManager { public synchronized void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache clonedDefaultCache = cloneDefaultCache(cacheName); if (clonedDefaultCache == null) { throw new CacheException(NO_DEFAULT_CACHE_ERROR_MSG); } addCache(clonedDefaultCache); for (Ehcache ehcache : createDefaultCacheDecorators(clonedDefaultCache)) { addOrReplaceDecoratedCache(clonedDefaultCache, ehcache); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removeAllCaches(); @Deprecated void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); @Override String toString(); DiskStorePathManager getDiskStorePathManager(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); FeaturesManager getFeaturesManager(); void sendManagementEvent(Serializable event, String type); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCache() throws CacheException { Configuration config = new Configuration().defaultCache(new CacheConfiguration().maxEntriesLocalHeap(0)); CacheManager manager = new CacheManager(config); try { assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); manager.addCache("test"); manager.addCache("test2"); assertEquals(2, manager.getConfiguration().getCacheConfigurations().size()); Ehcache cache = manager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = manager.getCacheNames(); boolean match = false; for (String cacheName : cacheNames) { if (cacheName.equals("test")) { match = true; } } assertTrue(match); manager.addCache(""); assertEquals(2, manager.getConfiguration().getCacheConfigurations().size()); } finally { manager.shutdown(); } } |
### Question:
EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats { public boolean isRegionCacheOrphanEvictionEnabled(String region) { Cache cache = this.cacheManager.getCache(region); if (cache != null && cache.isTerracottaClustered()) { return cache.getCacheConfiguration().getTerracottaConfiguration().getOrphanEviction(); } else { return false; } } EhcacheStatsImpl(CacheManager manager); void flushRegionCache(String region); void flushRegionCaches(); String generateActiveConfigDeclaration(); String generateActiveConfigDeclaration(String region); long getCacheHitCount(); double getCacheHitRate(); long getCacheHitSample(); long getCacheMissCount(); double getCacheMissRate(); long getCacheMissSample(); long getCachePutCount(); double getCachePutRate(); long getCachePutSample(); String getOriginalConfigDeclaration(); String getOriginalConfigDeclaration(String region); Map<String, Map<String, Object>> getRegionCacheAttributes(); Map<String, Object> getRegionCacheAttributes(String regionName); int getRegionCacheMaxTTISeconds(String region); int getRegionCacheMaxTTLSeconds(String region); int getRegionCacheOrphanEvictionPeriod(String region); Map<String, int[]> getRegionCacheSamples(); int getRegionCacheTargetMaxInMemoryCount(String region); int getRegionCacheTargetMaxTotalCount(String region); String[] getTerracottaHibernateCacheRegionNames(); boolean isRegionCacheEnabled(String region); void setRegionCacheEnabled(String region, boolean enabled); boolean isRegionCachesEnabled(); void setRegionCachesEnabled(final boolean flag); boolean isRegionCacheLoggingEnabled(String region); boolean isRegionCacheOrphanEvictionEnabled(String region); boolean isTerracottaHibernateCache(String region); void setRegionCacheLoggingEnabled(String region, boolean loggingEnabled); void setRegionCacheMaxTTISeconds(String region, int maxTTISeconds); void setRegionCacheMaxTTLSeconds(String region, int maxTTLSeconds); void setRegionCacheTargetMaxInMemoryCount(String region, int targetMaxInMemoryCount); void setRegionCacheTargetMaxTotalCount(String region, int targetMaxTotalCount); int getNumberOfElementsInMemory(String region); int getNumberOfElementsOffHeap(String region); int getNumberOfElementsOnDisk(String region); long getMaxGetTimeMillis(); long getMinGetTimeMillis(); long getMaxGetTimeMillis(String cacheName); long getMinGetTimeMillis(String cacheName); float getAverageGetTimeMillis(String region); @Override MBeanNotificationInfo[] getNotificationInfo(); }### Answer:
@Test public void testIsRegionCacheOrphanEvictionEnabled() { assertThat(stats.isRegionCacheOrphanEvictionEnabled("sampleCache1"), is(false)); } |
### Question:
ToolkitInstanceFactoryImpl implements ToolkitInstanceFactory { void addCacheEntityInfo(final String cacheName, final CacheConfiguration ehcacheConfig, String toolkitCacheName) { if (clusteredCacheManagerEntity == null) { throw new IllegalStateException(format("ClusteredCacheManger entity not configured for cache %s", cacheName)); } ClusteredCache cacheEntity = clusteredCacheManagerEntity.getCache(cacheName); if (cacheEntity == null) { ToolkitReadWriteLock cacheRWLock = clusteredCacheManagerEntity.getCacheLock(cacheName); ToolkitLock cacheWriteLock = cacheRWLock.writeLock(); while (true) { if (cacheWriteLock.tryLock()) { try { cacheEntity = createClusteredCacheEntity(cacheName, ehcacheConfig, toolkitCacheName); } finally { cacheWriteLock.unlock(); } } else { cacheEntity = clusteredCacheManagerEntity.getCache(cacheName); } if (cacheEntity != null) { break; } } } clusteredCacheManagerEntity.markCacheInUse(cacheEntity); } ToolkitInstanceFactoryImpl(TerracottaClientConfiguration terracottaClientConfiguration); ToolkitInstanceFactoryImpl(Toolkit toolkit, ClusteredEntityManager clusteredEntityManager); @Override void waitForOrchestrator(String cacheManagerName); @Override void markCacheWanDisabled(String cacheManagerName, String cacheName); @Override Toolkit getToolkit(); @Override ToolkitCacheInternal<String, Serializable> getOrCreateToolkitCache(final Ehcache cache); @Override ToolkitCacheInternal<String, Serializable> getOrCreateWanAwareToolkitCache(final String cacheManagerName,
final String cacheName,
final CacheConfiguration ehcacheConfig); @Override ToolkitNotifier<CacheConfigChangeNotificationMsg> getOrCreateConfigChangeNotifier(Ehcache cache); @Override ToolkitNotifier<CacheEventNotificationMsg> getOrCreateCacheEventNotifier(Ehcache cache); @Override ToolkitNotifier<CacheDisposalNotification> getOrCreateCacheDisposalNotifier(Ehcache cache); @Override String getFullyQualifiedCacheName(Ehcache cache); @Override ToolkitLock getOrCreateStoreLock(Ehcache cache); @Override ToolkitMap<String, AttributeExtractor> getOrCreateExtractorsMap(Ehcache cache); @Override ToolkitMap<String, String> getOrCreateAttributeMap(Ehcache cache); @Override void shutdown(); @Override SerializedToolkitCache<ClusteredSoftLockIDKey, SerializedReadCommittedClusteredSoftLock> getOrCreateAllSoftLockMap(String cacheManagerName,
String cacheName); @Override ToolkitMap<SerializedReadCommittedClusteredSoftLock, Integer> getOrCreateNewSoftLocksSet(String cacheManagerName,
String cacheName); @Override ToolkitMap<String, AsyncConfig> getOrCreateAsyncConfigMap(); @Override ToolkitMap<String, Set<String>> getOrCreateAsyncListNamesMap(String fullAsyncName); @Override ToolkitMap<String, Serializable> getOrCreateClusteredStoreConfigMap(String cacheManagerName, String cacheName); @Override SerializedToolkitCache<TransactionID, Decision> getOrCreateTransactionCommitStateMap(String cacheManagerName); @Override ToolkitLock getSoftLockWriteLock(String cacheManagerName, String cacheName, TransactionID transactionID,
Object key); @Override ToolkitLock getLockForCache(Ehcache cache, String lockName); @Override ToolkitReadWriteLock getSoftLockFreezeLock(String cacheManagerName, String cacheName,
TransactionID transactionID, Object key); @Override ToolkitReadWriteLock getSoftLockNotifierLock(String cacheManagerName, String cacheName,
TransactionID transactionID, Object key); @Override boolean destroy(final String cacheManagerName, final String cacheName); @Override void removeNonStopConfigforCache(Ehcache cache); @Override void linkClusteredCacheManager(String cacheManagerName, net.sf.ehcache.config.Configuration configuration); @Override void unlinkCache(String cacheName); static final String DELIMITER; }### Answer:
@Test public void testAddCacheEntityInfo() { factory.addCacheEntityInfo(CACHE_NAME, new CacheConfiguration(), "testTKCacheName"); } |
### Question:
EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats { public int getRegionCacheOrphanEvictionPeriod(String region) { Cache cache = this.cacheManager.getCache(region); if (cache != null && cache.isTerracottaClustered()) { return cache.getCacheConfiguration().getTerracottaConfiguration().getOrphanEvictionPeriod(); } else { return -1; } } EhcacheStatsImpl(CacheManager manager); void flushRegionCache(String region); void flushRegionCaches(); String generateActiveConfigDeclaration(); String generateActiveConfigDeclaration(String region); long getCacheHitCount(); double getCacheHitRate(); long getCacheHitSample(); long getCacheMissCount(); double getCacheMissRate(); long getCacheMissSample(); long getCachePutCount(); double getCachePutRate(); long getCachePutSample(); String getOriginalConfigDeclaration(); String getOriginalConfigDeclaration(String region); Map<String, Map<String, Object>> getRegionCacheAttributes(); Map<String, Object> getRegionCacheAttributes(String regionName); int getRegionCacheMaxTTISeconds(String region); int getRegionCacheMaxTTLSeconds(String region); int getRegionCacheOrphanEvictionPeriod(String region); Map<String, int[]> getRegionCacheSamples(); int getRegionCacheTargetMaxInMemoryCount(String region); int getRegionCacheTargetMaxTotalCount(String region); String[] getTerracottaHibernateCacheRegionNames(); boolean isRegionCacheEnabled(String region); void setRegionCacheEnabled(String region, boolean enabled); boolean isRegionCachesEnabled(); void setRegionCachesEnabled(final boolean flag); boolean isRegionCacheLoggingEnabled(String region); boolean isRegionCacheOrphanEvictionEnabled(String region); boolean isTerracottaHibernateCache(String region); void setRegionCacheLoggingEnabled(String region, boolean loggingEnabled); void setRegionCacheMaxTTISeconds(String region, int maxTTISeconds); void setRegionCacheMaxTTLSeconds(String region, int maxTTLSeconds); void setRegionCacheTargetMaxInMemoryCount(String region, int targetMaxInMemoryCount); void setRegionCacheTargetMaxTotalCount(String region, int targetMaxTotalCount); int getNumberOfElementsInMemory(String region); int getNumberOfElementsOffHeap(String region); int getNumberOfElementsOnDisk(String region); long getMaxGetTimeMillis(); long getMinGetTimeMillis(); long getMaxGetTimeMillis(String cacheName); long getMinGetTimeMillis(String cacheName); float getAverageGetTimeMillis(String region); @Override MBeanNotificationInfo[] getNotificationInfo(); }### Answer:
@Test public void testGetRegionCacheOrphanEvictionPeriod() { assertThat(stats.getRegionCacheOrphanEvictionPeriod("sampleCache1"), is(-1)); } |
### Question:
Element implements Serializable, Cloneable { @Deprecated public final Serializable getKey() throws CacheException { try { return (Serializable) getObjectKey(); } catch (ClassCastException e) { throw new CacheException("The key " + getObjectKey() + " is not Serializable. Consider using Element.getObjectKey()"); } } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime, final long nextToLastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime,
final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan,
final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value,
final int timeToIdleSeconds, final int timeToLiveSeconds); Element(final Object key, final Object value, final boolean eternal); @Deprecated Element(final Object key, final Object value,
final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); @Deprecated final Serializable getKey(); final Object getObjectKey(); @Deprecated final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer:
@Test public void testGetKeyThrowsCacheExceptionOnAccessingNonSerializableKey() { Object key = new Object() { @Override public String toString() { return "HAHA!"; } }; Object value = new Object(); Element element = new Element(key, value); try { element.getKey(); fail("element.getKey() did not throw"); } catch (CacheException e) { assertThat(e.getMessage(), equalTo("The key HAHA! is not Serializable. Consider using Element.getObjectKey()")); } } |
### Question:
Element implements Serializable, Cloneable { @Deprecated public final Serializable getValue() throws CacheException { try { return (Serializable) getObjectValue(); } catch (ClassCastException e) { throw new CacheException("The value " + getObjectValue() + " for key " + getObjectKey() + " is not Serializable. Consider using Element.getObjectValue()"); } } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime, final long nextToLastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime,
final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan,
final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value,
final int timeToIdleSeconds, final int timeToLiveSeconds); Element(final Object key, final Object value, final boolean eternal); @Deprecated Element(final Object key, final Object value,
final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); @Deprecated final Serializable getKey(); final Object getObjectKey(); @Deprecated final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer:
@Test public void testGetValueThrowsCacheExceptionOnAccessingNonSerializableValue() { Object key = new Object() { @Override public String toString() { return "daKey"; } }; Object value = new Object() { @Override public String toString() { return "HOHO!"; } }; Element element = new Element(key, value); try { element.getValue(); fail(); } catch (CacheException e) { assertThat(e.getMessage(), equalTo("The value HOHO! for key daKey is not Serializable. Consider using Element.getObjectValue()")); } } |
### Question:
Element implements Serializable, Cloneable { public final boolean isSerializable() { return isKeySerializable() && (value instanceof Serializable || value == null); } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime, final long nextToLastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime,
final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan,
final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value,
final int timeToIdleSeconds, final int timeToLiveSeconds); Element(final Object key, final Object value, final boolean eternal); @Deprecated Element(final Object key, final Object value,
final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); @Deprecated final Serializable getKey(); final Object getObjectKey(); @Deprecated final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer:
@Test public void testNullsAreSerializable() { Element element = new Element(null, null); assertTrue(element.isSerializable()); Element elementWithNullValue = new Element("1", null); assertTrue(elementWithNullValue.isSerializable()); Element elementWithNullKey = new Element(null, "1"); assertTrue(elementWithNullKey.isSerializable()); }
@Test public void testSerializableIsSerializable() { Element element = new Element("I'm with", "idiot"); assertTrue(element.isSerializable()); }
@Test public void testNonSerializableAreNotSerializable() { Element elementWithObjectKey = new Element(new Object(), "1"); assertFalse(elementWithObjectKey.isSerializable()); Element elementWithObjectValue = new Element("1", new Object()); assertFalse(elementWithObjectValue.isSerializable()); Element elementWithObjectKeyAndValue = new Element(new Object(), new Object()); assertFalse(elementWithObjectKeyAndValue.isSerializable()); }
@Test public void testIsSerializable() { Element element = new Element(null, null); assertTrue(element.isSerializable()); Element elementWithNullValue = new Element("1", null); assertTrue(elementWithNullValue.isSerializable()); Element elementWithNullKey = new Element(null, "1"); assertTrue(elementWithNullValue.isSerializable()); Element elementWithObjectKey = new Element(new Object(), "1"); assertTrue(elementWithNullValue.isSerializable()); } |
### Question:
OnHeapCachingTier implements CachingTier<K, V> { @Override public V get(final K key, final Callable<V> source, final boolean updateStats) { if (updateStats) { getObserver.begin(); } Object cachedValue = backEnd.get(key); if (cachedValue == null) { if (updateStats) { getObserver.end(GetOutcome.MISS); } Fault<V> f = new Fault<V>(source); cachedValue = backEnd.putIfAbsent(key, f); if (cachedValue == null) { try { V value = f.get(); putObserver.begin(); if (value == null) { backEnd.remove(key, f); } else if (backEnd.replace(key, f, value)) { putObserver.end(PutOutcome.ADDED); } else { return null; } return value; } catch (Throwable e) { backEnd.remove(key, f); if (e instanceof RuntimeException) { throw (RuntimeException)e; } else { throw new CacheException(e); } } } } else { if (updateStats) { getObserver.end(GetOutcome.HIT); } } return getValue(cachedValue); } OnHeapCachingTier(final HeapCacheBackEnd<K, Object> backEnd); static OnHeapCachingTier<Object, Element> createOnHeapCache(final Ehcache cache, final Pool onHeapPool); @Override boolean loadOnPut(); @Override V get(final K key, final Callable<V> source, final boolean updateStats); @Override V remove(final K key); @Override void clear(); @Override void addListener(final Listener<K, V> listener); @Statistic(name = "size", tags = "local-heap") @Override int getInMemorySize(); @Override int getOffHeapSize(); @Override boolean contains(final K key); @Statistic(name = "size-in-bytes", tags = "local-heap") @Override long getInMemorySizeInBytes(); @Override long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override void recalculateSize(final K key); @Override Policy getEvictionPolicy(); @Override void setEvictionPolicy(final Policy policy); }### Answer:
@Test public void testOnlyPopulatesOnce() throws InterruptedException, BrokenBarrierException { final int threadCount = Runtime.getRuntime().availableProcessors() * 2; final CachingTier<String, String> cache = new OnHeapCachingTier<String, String>(new CountBasedBackEnd<String, Object>(threadCount * 2)); final AtomicBoolean failure = new AtomicBoolean(); final AtomicInteger invocationCounter = new AtomicInteger(); final AtomicInteger valuesRead = new AtomicInteger(); final CyclicBarrier barrier = new CyclicBarrier(threadCount + 1); final Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread() { @Override public void run() { try { final int await = barrier.await(); cache.get(KEY, new Callable<String>() { @Override public String call() throws Exception { invocationCounter.incrementAndGet(); return "0x" + Integer.toHexString(await); } }, false); valuesRead.getAndIncrement(); } catch (Exception e) { e.printStackTrace(); failure.set(true); } } }; threads[i].start(); } barrier.await(); for (Thread thread : threads) { thread.join(); } assertThat(failure.get(), is(false)); assertThat(invocationCounter.get(), is(1)); assertThat(valuesRead.get(), is(threadCount)); } |
### Question:
CopyStrategyHandler { boolean isCopyActive() { return copyOnRead || copyOnWrite; } CopyStrategyHandler(boolean copyOnRead, boolean copyOnWrite, ReadWriteCopyStrategy<Element> copyStrategy); Element copyElementForReadIfNeeded(Element element); }### Answer:
@Test public void given_no_copy_when_isCopyActive_then_false() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, false, null); assertThat(copyStrategyHandler.isCopyActive(), is(false)); }
@Test public void given_copy_on_read_when_isCopyActive_then_false() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy); assertThat(copyStrategyHandler.isCopyActive(), is(true)); }
@Test public void given_copy_on_write_when_isCopyActive_then_false() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy); assertThat(copyStrategyHandler.isCopyActive(), is(true)); }
@Test public void given_copy_on_read_and_write_when_isCopyActive_then_false() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy); assertThat(copyStrategyHandler.isCopyActive(), is(true)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.