0001: /**
0002: * Copyright 2003-2007 Luck Consulting Pty Ltd
0003: *
0004: * Licensed under the Apache License, Version 2.0 (the "License");
0005: * you may not use this file except in compliance with the License.
0006: * You may obtain a copy of the License at
0007: *
0008: * http://www.apache.org/licenses/LICENSE-2.0
0009: *
0010: * Unless required by applicable law or agreed to in writing, software
0011: * distributed under the License is distributed on an "AS IS" BASIS,
0012: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0013: * See the License for the specific language governing permissions and
0014: * limitations under the License.
0015: */package net.sf.ehcache.jcache;
0016:
0017: import edu.emory.mathcs.backport.java.util.concurrent.ExecutionException;
0018: import net.sf.ehcache.exceptionhandler.CountingExceptionHandler;
0019: import net.sf.ehcache.loader.CountingCacheLoader;
0020: import net.sf.ehcache.loader.ExceptionThrowingLoader;
0021: import net.sf.ehcache.Ehcache;
0022: import net.sf.ehcache.AbstractCacheTest;
0023: import net.sf.ehcache.StopWatch;
0024: import net.sf.ehcache.ThreadKiller;
0025: import net.sf.ehcache.Element;
0026: import net.sf.jsr107cache.Cache;
0027: import net.sf.jsr107cache.CacheEntry;
0028: import net.sf.jsr107cache.CacheException;
0029: import net.sf.jsr107cache.CacheManager;
0030: import net.sf.jsr107cache.CacheStatistics;
0031: import org.apache.commons.logging.Log;
0032: import org.apache.commons.logging.LogFactory;
0033:
0034: import java.io.Serializable;
0035: import java.util.ArrayList;
0036: import java.util.Collection;
0037: import java.util.Date;
0038: import java.util.HashMap;
0039: import java.util.List;
0040: import java.util.Map;
0041: import java.util.Random;
0042: import java.util.Set;
0043:
0044: /**
0045: * Tests for a Cache
0046: *
0047: * @author Greg Luck
0048: * @version $Id:JCacheTest.java 318 2007-01-25 01:48:35Z gregluck $
0049: */
0050: public class JCacheTest extends AbstractCacheTest {
0051: private static final Log LOG = LogFactory.getLog(JCacheTest.class
0052: .getName());
0053:
0054: /**
0055: * setup test
0056: */
0057: protected void setUp() throws Exception {
0058: super .setUp();
0059: System.gc();
0060: Thread.sleep(100);
0061: System.gc();
0062: }
0063:
0064: /**
0065: * teardown
0066: * limits to what we can do here under jsr107
0067: */
0068: protected void tearDown() throws Exception {
0069: getTest1Cache().clear();
0070: getTest2Cache().clear();
0071: getTest4Cache().clear();
0072: manager.getEhcache("sampleCache1").removeAll();
0073: }
0074:
0075: /**
0076: * Gets the sample cache 1
0077: * <cache name="sampleCache1"
0078: * maxElementsInMemory="10000"
0079: * maxElementsOnDisk="1000"
0080: * eternal="false"
0081: * timeToIdleSeconds="360"
0082: * timeToLiveSeconds="1000"
0083: * overflowToDisk="true"
0084: * memoryStoreEvictionPolicy="LRU">
0085: * <cacheEventListenerFactory class="net.sf.ehcache.event.NullCacheEventListenerFactory"/>
0086: * </cache>
0087: */
0088: protected JCache getTest1Cache() throws CacheException {
0089: Cache cache = CacheManager.getInstance().getCache("test1");
0090: if (cache == null) {
0091: //sampleCache1
0092: Map env = new HashMap();
0093: env.put("name", "test1");
0094: env.put("maxElementsInMemory", "10000");
0095: env.put("maxElementsOnDisk", "1000");
0096: env.put("memoryStoreEvictionPolicy", "LRU");
0097: env.put("overflowToDisk", "true");
0098: env.put("eternal", "false");
0099: env.put("timeToLiveSeconds", "1000");
0100: env.put("timeToIdleSeconds", "1000");
0101: env.put("diskPersistent", "false");
0102: env.put("diskExpiryThreadIntervalSeconds", "120");
0103: env.put("cacheLoaderFactoryClassName",
0104: "net.sf.ehcache.loader.CountingCacheLoaderFactory");
0105: cache = CacheManager.getInstance().getCacheFactory()
0106: .createCache(env);
0107: CacheManager.getInstance().registerCache("test1", cache);
0108: }
0109: return (JCache) CacheManager.getInstance().getCache("test1");
0110: }
0111:
0112: private Cache getTest2Cache() throws CacheException {
0113: Cache cache = CacheManager.getInstance().getCache("test2");
0114: if (cache == null) {
0115: Map env = new HashMap();
0116: env.put("name", "test2");
0117: env.put("maxElementsInMemory", "1");
0118: env.put("overflowToDisk", "true");
0119: env.put("eternal", "false");
0120: env.put("timeToLiveSeconds", "1");
0121: env.put("timeToIdleSeconds", "0");
0122: cache = CacheManager.getInstance().getCacheFactory()
0123: .createCache(env);
0124: CacheManager.getInstance().registerCache("test2", cache);
0125: }
0126: return CacheManager.getInstance().getCache("test2");
0127: }
0128:
0129: private Cache getTest4Cache() throws CacheException {
0130: Cache cache = CacheManager.getInstance().getCache("test4");
0131: if (cache == null) {
0132: Map env = new HashMap();
0133: env.put("name", "test4");
0134: env.put("maxElementsInMemory", "1000");
0135: env.put("overflowToDisk", "true");
0136: env.put("eternal", "true");
0137: env.put("timeToLiveSeconds", "0");
0138: env.put("timeToIdleSeconds", "0");
0139: cache = CacheManager.getInstance().getCacheFactory()
0140: .createCache(env);
0141: CacheManager.getInstance().registerCache("test4", cache);
0142: }
0143: return CacheManager.getInstance().getCache("test4");
0144: }
0145:
0146: /**
0147: * Checks we cannot use a cache after shutdown
0148: * test cannot be implemented due to lack of lifecycle support in jsr107
0149: */
0150: // public void testUseCacheAfterManagerShutdown() throws CacheException {
0151: /**
0152: * Checks we cannot use a cache outside the manager
0153: * Is the jsr107 silent on whether you can do this?
0154: */
0155: // public void testUseCacheOutsideManager() throws CacheException {
0156: /**
0157: * Checks when and how we can set the cache name.
0158: * This is not allowed in jsr107
0159: */
0160: //public void testSetCacheName() throws CacheException {
0161: /**
0162: * Test using a cache which has been removed and replaced.
0163: * Is the jsr107 silent on whether you can do this?
0164: */
0165: // public void testStaleCacheReference() throws CacheException {
0166: /**
0167: * Tests getting the cache name
0168: * there is no getName method in jsr107
0169: *
0170: * @throws Exception
0171: */
0172: // public void testCacheWithNoIdle() throws Exception {
0173: /**
0174: * Test expiry based on time to live
0175: * <cache name="sampleCacheNoIdle"
0176: * maxElementsInMemory="1000"
0177: * eternal="false"
0178: * timeToLiveSeconds="5"
0179: * overflowToDisk="false"
0180: * />
0181: */
0182: public void testExpiryBasedOnTimeToLiveWhenNoIdle()
0183: throws Exception {
0184: net.sf.ehcache.Cache ehcache = manager
0185: .getCache("sampleCacheNoIdle");
0186: JCache jCache = new JCache(ehcache, null);
0187: manager.replaceEhcacheWithJCache(ehcache, jCache);
0188:
0189: Cache cache = manager.getJCache("sampleCacheNoIdle");
0190: cache.put("key1", "value1");
0191: cache.put("key2", "value1");
0192: assertNotNull(cache.get("key1"));
0193: assertNotNull(cache.get("key2"));
0194:
0195: //Test time to idle. Should not idle out because not specified
0196: Thread.sleep(2000);
0197: assertNotNull(cache.get("key1"));
0198: assertNotNull(cache.get("key2"));
0199:
0200: //Test time to live.
0201: Thread.sleep(5020);
0202: assertNull(cache.get("key1"));
0203: assertNull(cache.get("key2"));
0204: }
0205:
0206: /**
0207: * Test expiry based on time to live where an Eelment override is set on TTL
0208: * jsr107 does not support TTL overrides per put.
0209: */
0210: // public void testExpiryBasedOnTimeToLiveWhenNoIdleElementOverride() throws Exception {
0211: /**
0212: * Test overflow to disk = false
0213: */
0214: public void testNoOverflowToDisk() throws Exception {
0215: Ehcache ehcache = new net.sf.ehcache.Cache(
0216: "testNoOverflowToDisk", 1, false, true, 500, 200);
0217: manager.addCache(ehcache);
0218: Cache cache = new JCache(ehcache, null);
0219: cache.put("key1", "value1");
0220: cache.put("key2", "value1");
0221: assertNull(cache.get("key1"));
0222: assertNotNull(cache.get("key2"));
0223: }
0224:
0225: /**
0226: * Test isEmpty
0227: */
0228: public void testIsEmpty() throws Exception {
0229: Ehcache ehcache = new net.sf.ehcache.Cache("testIsEmpty", 1,
0230: true, true, 500, 200);
0231: manager.addCache(ehcache);
0232: Cache cache = new JCache(ehcache, null);
0233: assertTrue(cache.isEmpty());
0234:
0235: cache.put("key1", "value1");
0236: assertFalse(cache.isEmpty());
0237: cache.put("key2", "value1");
0238: assertFalse(cache.isEmpty());
0239:
0240: assertNotNull(cache.get("key1"));
0241: assertNotNull(cache.get("key2"));
0242: }
0243:
0244: /**
0245: * Create a JCache from an inactive Ehcache and try adding to CacheManager.
0246: * <p/>
0247: * Check that getting JCache, Ehcache and Cache all make sense.
0248: */
0249: public void testEhcacheConstructor() throws Exception {
0250: Ehcache ehcache = new net.sf.ehcache.Cache(
0251: "testJCacheCreation", 1, true, true, 500, 200);
0252: JCache cache = new JCache(ehcache);
0253: manager.addCache(cache);
0254:
0255: JCache jCacheFromCacheManager = manager
0256: .getJCache("testJCacheCreation");
0257: assertTrue(jCacheFromCacheManager.isEmpty());
0258:
0259: Ehcache ehcacheFromCacheManager = manager
0260: .getEhcache("testJCacheCreation");
0261: assertEquals(0, ehcacheFromCacheManager.getSize());
0262:
0263: net.sf.ehcache.Cache cacheFromCacheManager = manager
0264: .getCache("testJCacheCreation");
0265: assertEquals(0, cacheFromCacheManager.getSize());
0266:
0267: assertEquals(jCacheFromCacheManager.getBackingCache(),
0268: ehcacheFromCacheManager);
0269:
0270: assertEquals(jCacheFromCacheManager.getBackingCache(),
0271: cacheFromCacheManager);
0272:
0273: assertEquals(ehcacheFromCacheManager, cacheFromCacheManager);
0274:
0275: }
0276:
0277: /**
0278: * Test isEmpty
0279: */
0280: public void testEvict() throws Exception {
0281: Ehcache ehcache = new net.sf.ehcache.Cache("testEvict", 1,
0282: true, false, 1, 200);
0283: manager.addCache(ehcache);
0284: Cache cache = new JCache(ehcache, null);
0285: assertTrue(cache.isEmpty());
0286:
0287: cache.put("key1", "value1");
0288: cache.put("key2", "value1");
0289: //no invalid
0290: cache.evict();
0291: assertFalse(cache.isEmpty());
0292:
0293: Thread.sleep(1020);
0294: cache.evict();
0295: assertNull(cache.get("key1"));
0296: assertNull(cache.get("key2"));
0297:
0298: cache.put("key1", "value1");
0299: cache.put("key2", "value1");
0300: Thread.sleep(1020);
0301: assertNull(cache.get("key1"));
0302: assertNull(cache.get("key2"));
0303:
0304: }
0305:
0306: /**
0307: * Test containsKey
0308: */
0309: public void testContainsKey() throws Exception {
0310: Ehcache ehcache = new net.sf.ehcache.Cache("testContainsKey",
0311: 1, true, true, 500, 200);
0312: manager.addCache(ehcache);
0313: Cache cache = new JCache(ehcache, null);
0314: assertFalse(cache.containsKey("key1"));
0315: assertFalse(cache.containsKey("key2"));
0316:
0317: cache.put("key1", "value1");
0318: assertTrue(cache.containsKey("key1"));
0319: assertFalse(cache.containsKey("key2"));
0320:
0321: cache.put("key2", "value1");
0322: assertTrue(cache.containsKey("key1"));
0323: assertTrue(cache.containsKey("key2"));
0324:
0325: assertNotNull(cache.get("key1"));
0326: assertNotNull(cache.get("key2"));
0327: }
0328:
0329: /**
0330: * Test containsValue
0331: */
0332: public void testContainsValue() throws Exception {
0333: Ehcache ehcache = new net.sf.ehcache.Cache("testContainsValue",
0334: 2, true, true, 500, 200);
0335: manager.addCache(ehcache);
0336: Cache cache = new JCache(ehcache, null);
0337: assertFalse(cache.containsValue("value1"));
0338: assertFalse(cache.containsValue(null));
0339:
0340: cache.put("key1", null);
0341: assertFalse(cache.containsValue("value1"));
0342: assertTrue(cache.containsValue(null));
0343:
0344: cache.put("key2", "value1");
0345: assertTrue(cache.containsValue("value1"));
0346: assertTrue(cache.containsValue(null));
0347:
0348: assertNull(cache.get("key1"));
0349: assertNotNull(cache.get("key2"));
0350: }
0351:
0352: /**
0353: * Test the get method.
0354: */
0355: public void testGet() throws Exception {
0356: Ehcache ehcache = new net.sf.ehcache.Cache("testGet", 10, true,
0357: true, 500, 200);
0358: manager.addCache(ehcache);
0359: JCache jcache = new JCache(manager.getCache("sampleCache1"),
0360: null);
0361: CountingCacheLoader specificCacheLoader = new CountingCacheLoader();
0362: specificCacheLoader.setName("SpecificCacheLoader");
0363:
0364: //existing entry with dog value, no loader
0365: jcache.put("key", "dog");
0366: Object value = jcache.get("key");
0367: assertEquals("dog", value);
0368:
0369: //existing entry with dog value, with loader
0370: CountingCacheLoader countingCacheLoader = new CountingCacheLoader();
0371: jcache.setCacheLoader(countingCacheLoader);
0372: value = jcache.get("key");
0373: assertEquals("dog", value);
0374:
0375: //existing entry with dog value, with loader and loaderArgument
0376: countingCacheLoader = new CountingCacheLoader();
0377: jcache.setCacheLoader(countingCacheLoader);
0378: value = jcache.get("key", "1");
0379: assertEquals("dog", value);
0380:
0381: //no entry with matching key in cache, no loader
0382: jcache.remove("key");
0383: jcache.setCacheLoader(null);
0384: jcache.put("key", null);
0385: value = jcache.get("key");
0386: assertNull(value);
0387:
0388: //no entry with matching key in cache, no loader, and loaderArgument
0389: jcache.remove("key");
0390: jcache.setCacheLoader(null);
0391: jcache.put("key", null);
0392: value = jcache.get("key", "loaderArgument");
0393: assertNull(value);
0394:
0395: //no entry with matching key in cache, with loader
0396: jcache.remove("key");
0397: jcache.setCacheLoader(countingCacheLoader);
0398: value = jcache.get("key");
0399: assertEquals(new Integer(0), value);
0400: jcache.remove("key");
0401: value = jcache.get("key");
0402: assertEquals(new Integer(1), value);
0403:
0404: //As above with an overridden loader
0405: jcache.remove("key");
0406: jcache.setCacheLoader(countingCacheLoader);
0407: value = jcache.get("key", new CountingCacheLoader());
0408: //counter back to 0 because this we overrode with a new loader
0409: assertEquals(new Integer(0), value);
0410:
0411: //no entry with no matching key in cache, with loader and loaderArgument. Our loader just returns the
0412: // loader name catendated with the loaderArgument
0413: jcache.remove("key");
0414: jcache.setCacheLoader(countingCacheLoader);
0415: value = jcache.get("key", "argumentValue");
0416: assertEquals("CountingCacheLoader:argumentValue", value);
0417:
0418: //As above with an overridden loader
0419: jcache.remove("key");
0420: jcache.setCacheLoader(countingCacheLoader);
0421: value = jcache.get("key", specificCacheLoader, "argumentValue");
0422: assertEquals("SpecificCacheLoader:argumentValue", value);
0423:
0424: //check original still works
0425: jcache.remove("key");
0426: jcache.setCacheLoader(countingCacheLoader);
0427: value = jcache.get("key", "argumentValue");
0428: assertEquals("CountingCacheLoader:argumentValue", value);
0429:
0430: //cache hit
0431: jcache.put("key2", "value");
0432: value = jcache.get("key2");
0433: assertEquals("value", value);
0434:
0435: }
0436:
0437: /**
0438: * Test the loader name method.
0439: */
0440: public void testLoaderName() throws Exception {
0441: Ehcache ehcache = new net.sf.ehcache.Cache("testName", 10,
0442: true, true, 500, 200);
0443: manager.addCache(ehcache);
0444: JCache jcache = new JCache(manager.getCache("sampleCache1"),
0445: null);
0446:
0447: //existing entry with dog value, with loader
0448: CountingCacheLoader countingCacheLoader = new CountingCacheLoader();
0449: jcache.setCacheLoader(countingCacheLoader);
0450:
0451: assertEquals("CountingCacheLoader", jcache.getCacheLoader()
0452: .getName());
0453:
0454: }
0455:
0456: /**
0457: * Test the get values method.
0458: */
0459: public void testGetValues() throws Exception {
0460: Ehcache ehcache = new net.sf.ehcache.Cache("testGetValue", 2,
0461: true, true, 500, 200);
0462: manager.addCache(ehcache);
0463:
0464: CountingCacheLoader countingCacheLoader = new CountingCacheLoader();
0465: JCache jcache = new JCache(manager.getCache("sampleCache1"),
0466: countingCacheLoader);
0467:
0468: /** A class which is not Serializable */
0469: class NonSerializable {
0470: }
0471:
0472: List keys = new ArrayList();
0473: for (int i = 0; i < 1000; i++) {
0474: keys.add(new Integer(i));
0475: }
0476: jcache.loadAll(keys);
0477: jcache.put(new Integer(1), new Date());
0478: jcache.put(new Integer(2), new NonSerializable());
0479: Thread.sleep((long) (3000 * StopWatch
0480: .getSpeedAdjustmentFactor()));
0481: assertEquals(1000, jcache.size());
0482:
0483: Collection values = jcache.values();
0484: assertEquals(1000, values.size());
0485:
0486: }
0487:
0488: /**
0489: * Tests putAll
0490: */
0491: public void testPutAll() {
0492: Ehcache ehcache = new net.sf.ehcache.Cache("testPutAll", 2,
0493: true, true, 500, 200);
0494: manager.addCache(ehcache);
0495: Cache cache = new JCache(ehcache, null);
0496: assertTrue(cache.isEmpty());
0497:
0498: cache.putAll(null);
0499: assertTrue(cache.isEmpty());
0500:
0501: cache.putAll(new HashMap());
0502: assertTrue(cache.isEmpty());
0503:
0504: Map map = new HashMap();
0505: for (int i = 0; i < 10; i++) {
0506: map.put(i + "", new Date());
0507: }
0508:
0509: cache.putAll(map);
0510: assertEquals(10, cache.size());
0511: }
0512:
0513: /**
0514: * Tests clear()
0515: */
0516: public void testClear() {
0517: Ehcache ehcache = new net.sf.ehcache.Cache("testClear", 2,
0518: true, true, 500, 200);
0519: manager.addCache(ehcache);
0520: Cache cache = new JCache(ehcache, null);
0521:
0522: assertTrue(cache.isEmpty());
0523: cache.clear();
0524: assertTrue(cache.isEmpty());
0525:
0526: cache.put("1", new Date());
0527: cache.clear();
0528: assertTrue(cache.isEmpty());
0529: }
0530:
0531: /**
0532: * Test the keyset method
0533: */
0534: public void testKeySet() {
0535: Ehcache ehcache = new net.sf.ehcache.Cache("testKeySet", 2,
0536: true, true, 500, 200);
0537: manager.addCache(ehcache);
0538: Cache cache = new JCache(ehcache, null);
0539:
0540: for (int i = 0; i < 10; i++) {
0541: cache.put(i + "", new Date());
0542: }
0543: //duplicate
0544: cache.put(0 + "", new Date());
0545: Set set = cache.keySet();
0546: assertEquals(10, set.size());
0547: }
0548:
0549: /**
0550: * Performance tests for a range of Memory Store - Disk Store combinations.
0551: * <p/>
0552: * This demonstrates that a memory only store is approximately an order of magnitude
0553: * faster than a disk only store.
0554: * <p/>
0555: * It also shows that double the performance of a Disk Only store can be obtained
0556: * with a maximum memory size of only 1. Accordingly a Cache created without a
0557: * maximum memory size of less than 1 will issue a warning.
0558: * <p/>
0559: * Threading changes were made in v1.41 of DiskStore. The before and after numbers are shown.
0560: */
0561: public void testProportionMemoryAndDiskPerformance()
0562: throws Exception {
0563: StopWatch stopWatch = new StopWatch();
0564: long time = 0;
0565:
0566: //Memory only Typical 192ms
0567: Ehcache ehcache = new net.sf.ehcache.Cache("testMemoryOnly",
0568: 5000, false, false, 5, 2);
0569: manager.addCache(ehcache);
0570: Cache memoryOnlyCache = new JCache(ehcache, null);
0571:
0572: time = stopWatch.getElapsedTime();
0573: for (int i = 0; i < 5000; i++) {
0574: Integer key = new Integer(i);
0575: memoryOnlyCache.put(new Integer(i), "value");
0576: memoryOnlyCache.get(key);
0577: }
0578: time = stopWatch.getElapsedTime();
0579: LOG.info("Time for MemoryStore: " + time);
0580: assertTrue("Time to put and get 5000 entries into MemoryStore",
0581: time < 300);
0582:
0583: //Set size so that all elements overflow to disk.
0584: // 1245 ms v1.38 DiskStore
0585: // 273 ms v1.42 DiskStore
0586: Ehcache diskOnlyEhcache = new net.sf.ehcache.Cache(
0587: "testDiskOnly", 0, true, false, 5, 2);
0588: manager.addCache(diskOnlyEhcache);
0589: Cache diskOnlyCache = new JCache(ehcache, null);
0590: time = stopWatch.getElapsedTime();
0591: for (int i = 0; i < 5000; i++) {
0592: Integer key = new Integer(i);
0593: diskOnlyCache.put(key, "value");
0594: diskOnlyCache.get(key);
0595: }
0596: time = stopWatch.getElapsedTime();
0597: LOG.info("Time for DiskStore: " + time);
0598: assertTrue(
0599: "Time to put and get 5000 entries into DiskStore was less than 2 sec",
0600: time < 2000);
0601:
0602: // 1 Memory, 999 Disk
0603: // 591 ms v1.38 DiskStore
0604: // 56 ms v1.42 DiskStore
0605: Ehcache m1d999Ehcache = new net.sf.ehcache.Cache("m1d999Cache",
0606: 1, true, false, 5, 2);
0607: manager.addCache(m1d999Ehcache);
0608: Cache m1d999Cache = new JCache(m1d999Ehcache, null);
0609: time = stopWatch.getElapsedTime();
0610: for (int i = 0; i < 5000; i++) {
0611: Integer key = new Integer(i);
0612: m1d999Cache.put(key, "value");
0613: m1d999Cache.get(key);
0614: }
0615: time = stopWatch.getElapsedTime();
0616: LOG.info("Time for m1d999Cache: " + time);
0617: assertTrue("Time to put and get 5000 entries into m1d999Cache",
0618: time < 2000);
0619:
0620: // 500 Memory, 500 Disk
0621: // 669 ms v1.38 DiskStore
0622: // 47 ms v1.42 DiskStore
0623: Ehcache m500d500Ehcache = new net.sf.ehcache.Cache(
0624: "m500d500Cache", 500, true, false, 5, 2);
0625: manager.addCache(m500d500Ehcache);
0626: Cache m500d500Cache = new JCache(m1d999Ehcache, null);
0627:
0628: time = stopWatch.getElapsedTime();
0629: for (int i = 0; i < 5000; i++) {
0630: Integer key = new Integer(i);
0631: m500d500Cache.put(key, "value");
0632: m500d500Cache.get(key);
0633: }
0634: time = stopWatch.getElapsedTime();
0635: LOG.info("Time for m500d500Cache: " + time);
0636: assertTrue(
0637: "Time to put and get 5000 entries into m500d500Cache",
0638: time < 2000);
0639:
0640: }
0641:
0642: /**
0643: * Test Caches with persistent stores dispose properly. Tests:
0644: * <ol>
0645: * <li>No exceptions are thrown on dispose
0646: * <li>You cannot re add a cache after it has been disposed and removed
0647: * <li>You can create a new cache with the same name
0648: * </ol>
0649: * jsr107 does not support lifecycles.
0650: */
0651: // public void testCreateAddDisposeAdd() throws CacheException {
0652: /**
0653: * Test expiry based on time to live
0654: */
0655: public void testExpiryBasedOnTimeToLive() throws Exception {
0656: //Set size so the second element overflows to disk.
0657: Ehcache ehcache = new net.sf.ehcache.Cache(
0658: "testExpiryBasedOnTimeToLive", 1, true, false, 3, 0);
0659: manager.addCache(ehcache);
0660: Cache cache = new JCache(ehcache, null);
0661:
0662: cache.put("key1", "value1");
0663: cache.put("key2", "value1");
0664:
0665: //Test time to live
0666: assertNotNull(cache.get("key1"));
0667: assertNotNull(cache.get("key2"));
0668: Thread.sleep(1020);
0669: //Test time to live
0670: assertNotNull(cache.get("key1"));
0671: assertNotNull(cache.get("key2"));
0672: Thread.sleep(1020);
0673: //Test time to live
0674: assertNotNull(cache.get("key1"));
0675: assertNotNull(cache.get("key2"));
0676: Thread.sleep(1020);
0677: assertNull(cache.get("key1"));
0678: assertNull(cache.get("key2"));
0679: }
0680:
0681: /**
0682: * Test expiry based on time to live where the TTL is set in the put
0683: */
0684: public void testExpiryBasedOnTimeToLiveTTL() throws Exception {
0685:
0686: //Set size so the second element overflows to disk.
0687: Ehcache ehcache = new net.sf.ehcache.Cache(
0688: "testExpiryBasedOnTimeToLiveTTL", 1, true, false, 3, 0);
0689: manager.addCache(ehcache);
0690: JCache cache = new JCache(ehcache, null);
0691:
0692: cache.put("key1", "value1", 1);
0693: //default
0694: cache.put("key2", "value1", 0);
0695:
0696: //Test time to live
0697: assertNotNull(cache.get("key1"));
0698: assertNotNull(cache.get("key2"));
0699:
0700: Thread.sleep(1020);
0701: //Test time to live
0702: assertNull(cache.get("key1"));
0703: assertNotNull(cache.get("key2"));
0704:
0705: Thread.sleep(2000);
0706: assertNull(cache.get("key1"));
0707: assertNull(cache.get("key2"));
0708:
0709: }
0710:
0711: /**
0712: * Test expiry based on time to live.
0713: * This test uses peek, which behaves the same as get
0714: */
0715: public void testExpiryBasedOnTimeToLiveUsingPeek() throws Exception {
0716: //Set size so the second element overflows to disk.
0717: Ehcache ehcache = new net.sf.ehcache.Cache(
0718: "testExpiryBasedOnTimeToLiveUsingPeek", 1, true, false,
0719: 3, 0);
0720: manager.addCache(ehcache);
0721: Cache cache = new JCache(ehcache, null);
0722:
0723: cache.put("key1", "value1");
0724: cache.put("key2", "value1");
0725:
0726: //Test time to live
0727: assertNotNull(cache.peek("key1"));
0728: assertNotNull(cache.peek("key2"));
0729: Thread.sleep(1020);
0730: //Test time to live
0731: assertNotNull(cache.peek("key1"));
0732: assertNotNull(cache.peek("key2"));
0733: Thread.sleep(1020);
0734: //Test time to live
0735: assertNotNull(cache.peek("key1"));
0736: assertNotNull(cache.peek("key2"));
0737: Thread.sleep(1020);
0738: assertNull(cache.peek("key1"));
0739: assertNull(cache.peek("key2"));
0740: }
0741:
0742: // /**
0743: // * Tests that a cache created from defaults will expire as per
0744: // * the default expiry policy.
0745: // * Caches cannot be created from default in jsr107
0746: // */
0747: // public void testExpiryBasedOnTimeToLiveForDefault() throws Exception {
0748:
0749: /**
0750: * Test expiry based on time to live.
0751: * <p/>
0752: * Elements are put quietly back into the cache after being cloned.
0753: * The elements should expire as if the putQuiet had not happened.
0754: * jsr107
0755: */
0756: // public void testExpiryBasedOnTimeToLiveAfterPutQuiet() throws Exception {
0757:
0758: /**
0759: * Test expiry based on time to live
0760: */
0761: public void testNoIdleOrExpiryBasedOnTimeToLiveForEternal()
0762: throws Exception {
0763: //Set size so the second element overflows to disk.
0764: Ehcache ehcache = new net.sf.ehcache.Cache(
0765: "testNoIdleOrExpiryBasedOnTimeToLiveForEternal", 1,
0766: true, true, 5, 2);
0767: manager.addCache(ehcache);
0768: Cache cache = new JCache(ehcache, null);
0769:
0770: cache.put("key1", "value1");
0771: cache.put("key2", "value1");
0772:
0773: //Test time to live
0774: assertNotNull(cache.get("key1"));
0775: assertNotNull(cache.get("key2"));
0776:
0777: //Check that we did not idle out
0778: Thread.sleep(2020);
0779: assertNotNull(cache.get("key1"));
0780: assertNotNull(cache.get("key2"));
0781:
0782: //Check that we did not expire out
0783: Thread.sleep(3020);
0784: assertNotNull(cache.get("key1"));
0785: assertNotNull(cache.get("key2"));
0786: }
0787:
0788: /**
0789: * Test expiry based on time to idle.
0790: */
0791: public void testExpiryBasedOnTimeToIdle() throws Exception {
0792: //Set size so the second element overflows to disk.
0793: Ehcache ehcache = new net.sf.ehcache.Cache(
0794: "testExpiryBasedOnTimeToIdle", 1, true, false, 6, 2);
0795: manager.addCache(ehcache);
0796: Cache cache = new JCache(ehcache, null);
0797:
0798: cache.put("key1", "value1");
0799: cache.put("key2", "value1");
0800:
0801: //Test time to idle
0802: assertNotNull(cache.get("key1"));
0803: assertNotNull(cache.get("key2"));
0804: Thread.sleep(2020);
0805: assertNull(cache.get("key1"));
0806: assertNull(cache.get("key2"));
0807:
0808: //Test effect of get
0809: cache.put("key1", "value1");
0810: cache.put("key2", "value1");
0811: Thread.sleep(1020);
0812: assertNotNull(cache.get("key1"));
0813: assertNotNull(cache.get("key2"));
0814:
0815: Thread.sleep(2020);
0816: assertNull(cache.get("key1"));
0817: assertNull(cache.get("key2"));
0818: }
0819:
0820: /**
0821: * Test expiry based on time to idle.
0822: * jsr107 has no put quiet
0823: */
0824: // public void testExpiryBasedOnTimeToIdleAfterPutQuiet() throws Exception {
0825: /**
0826: * Test element statistics, including get and getQuiet
0827: * eternal="false"
0828: * timeToIdleSeconds="5"
0829: * timeToLiveSeconds="10"
0830: * overflowToDisk="true"
0831: * <p/>
0832: * jsr107 has no put quiet
0833: */
0834: public void testElementStatistics() throws Exception {
0835: Ehcache ehcache = new net.sf.ehcache.Cache(
0836: "testElementStatistics", 1, true, false, 5, 2);
0837: manager.addCache(ehcache);
0838: Cache cache = new JCache(ehcache, null);
0839:
0840: cache.put("key1", "value1");
0841: cache.put("key2", "value1");
0842:
0843: CacheEntry cacheEntry = cache.getCacheEntry("key1");
0844: assertEquals("Should be one", 1, cacheEntry.getHits());
0845:
0846: cacheEntry = cache.getCacheEntry("key1");
0847: assertEquals("Should be two", 2, cacheEntry.getHits());
0848: }
0849:
0850: /**
0851: * Check getting a cache entry where it does not exist
0852: */
0853: public void testNullCacheEntry() {
0854: Ehcache ehcache = new net.sf.ehcache.Cache(
0855: "testNullCacheEntry", 1, true, false, 5, 2);
0856: manager.addCache(ehcache);
0857: Cache cache = new JCache(ehcache, null);
0858:
0859: cache.put("key1", "value1");
0860:
0861: CacheEntry cacheEntry = cache.getCacheEntry("key1");
0862: assertNotNull(cacheEntry);
0863: CacheEntry cacheEntry2 = cache.getCacheEntry("keyDoesNotExist");
0864: assertNull(cacheEntry2);
0865: }
0866:
0867: /**
0868: * Test cache statistics, including get.
0869: * Reconcile CacheEntry stats with cache stats and make sure they agree
0870: */
0871: public void testCacheStatistics() throws Exception {
0872: Ehcache ehcache = new net.sf.ehcache.Cache(
0873: "testCacheStatistics", 1, true, false, 5, 2);
0874: manager.addCache(ehcache);
0875: Cache cache = new JCache(ehcache, null);
0876: cache.put("key1", "value1");
0877: cache.put("key2", "value1");
0878:
0879: CacheEntry cacheEntry = cache.getCacheEntry("key1");
0880: assertEquals("Should be one", 1, cacheEntry.getHits());
0881: assertEquals("Should be one", 1, cache.getCacheStatistics()
0882: .getCacheHits());
0883:
0884: cacheEntry = cache.getCacheEntry("key1");
0885: assertEquals("Should be one", 2, cacheEntry.getHits());
0886: assertEquals("Should be one", 2, cache.getCacheStatistics()
0887: .getCacheHits());
0888:
0889: cacheEntry = cache.getCacheEntry("key2");
0890: assertEquals("Should be one", 1, cacheEntry.getHits());
0891: assertEquals("Should be one", 3, cache.getCacheStatistics()
0892: .getCacheHits());
0893:
0894: assertEquals("Should be 0", 0, cache.getCacheStatistics()
0895: .getCacheMisses());
0896: cache.get("doesnotexist");
0897: assertEquals("Should be 1", 1, cache.getCacheStatistics()
0898: .getCacheMisses());
0899:
0900: }
0901:
0902: /**
0903: * Checks that getQuiet works how we expect it to
0904: * not supported in jsr107
0905: */
0906: // public void testGetQuietAndPutQuiet() throws Exception {
0907: /**
0908: * Test size with put and remove.
0909: * <p/>
0910: * It checks that size makes sense, and also that getKeys.size() matches getSize()
0911: */
0912: public void testSizeWithPutAndRemove() throws Exception {
0913: //Set size so the second element overflows to disk.
0914: Ehcache ehcache = new net.sf.ehcache.Cache(
0915: "testSizeWithPutAndRemove", 1, true, true, 0, 0);
0916: manager.addCache(ehcache);
0917: Cache cache = new JCache(ehcache, null);
0918:
0919: cache.put("key1", "value1");
0920: cache.put("key2", "value1");
0921:
0922: int sizeFromGetSize = cache.getCacheStatistics()
0923: .getObjectCount();
0924: int sizeFromKeys = cache.keySet().size();
0925: assertEquals(sizeFromGetSize, sizeFromKeys);
0926: assertEquals(2, cache.getCacheStatistics().getObjectCount());
0927:
0928: /** A class which is not Serializable */
0929: class NonSerializable {
0930: }
0931:
0932: cache.put("key1", new NonSerializable());
0933: cache.put("key1", "value1");
0934:
0935: //key1 should be in the Disk Store
0936: assertEquals(cache.getCacheStatistics().getObjectCount(), cache
0937: .keySet().size());
0938: assertEquals(2, cache.getCacheStatistics().getObjectCount());
0939: //there were two of these, so size will now be one
0940: cache.remove("key1");
0941: assertEquals(cache.getCacheStatistics().getObjectCount(), cache
0942: .keySet().size());
0943: assertEquals(1, cache.getCacheStatistics().getObjectCount());
0944: cache.remove("key2");
0945: assertEquals(cache.getCacheStatistics().getObjectCount(), cache
0946: .keySet().size());
0947: assertEquals(0, cache.getCacheStatistics().getObjectCount());
0948:
0949: //try null values
0950: cache.clear();
0951: cache.put("nullValue1", null);
0952: cache.put("nullValue2", null);
0953: //Cannot overflow therefore just one
0954: assertEquals(1, cache.getCacheStatistics().getObjectCount());
0955: Object nullValue = cache.get("nullValue2");
0956: assertNull(nullValue);
0957:
0958: }
0959:
0960: /**
0961: * Test getKeys after expiry
0962: * <p/>
0963: * Makes sure that if an element is expired, its key should also be expired
0964: */
0965: public void testGetKeysAfterExpiry() throws Exception {
0966: //Set size so the second element overflows to disk.
0967: Cache cache = getTest2Cache();
0968: String key1 = "key1";
0969: cache.put(key1, "value1");
0970: cache.put("key2", "value1");
0971: //getSize uses getKeys().size(), so these should be the same
0972: assertEquals(cache.getCacheStatistics().getObjectCount(), cache
0973: .keySet().size());
0974: //getKeys does not do an expiry check, so the expired elements are counted
0975: assertEquals(2, cache.getCacheStatistics().getObjectCount());
0976: String keyFromDisk = (String) cache.getCacheEntry(key1)
0977: .getKey();
0978: assertTrue(key1.equals(keyFromDisk));
0979: Thread.sleep(1020);
0980: assertEquals(2, cache.keySet().size());
0981: //getKeysWithExpiryCheck does check and gives the correct answer of 0
0982: Ehcache ehcache = ((JCache) cache).getBackingCache();
0983: ehcache
0984: .setStatisticsAccuracy(CacheStatistics.STATISTICS_ACCURACY_GUARANTEED);
0985: assertEquals(0, cache.getCacheStatistics().getObjectCount());
0986: }
0987:
0988: /**
0989: * Test size after multiple calls, with put and remove
0990: */
0991: public void testSizeMultipleCallsWithPutAndRemove()
0992: throws Exception {
0993: //Set size so the second element overflows to disk.
0994: //Cache cache = new Cache("test3", 1, true, true, 0, 0);
0995: Cache cache = getTest2Cache();
0996: cache.put("key1", "value1");
0997: cache.put("key2", "value1");
0998:
0999: //key1 should be in the Disk Store
1000: assertEquals(2, cache.getCacheStatistics().getObjectCount());
1001: assertEquals(2, cache.getCacheStatistics().getObjectCount());
1002: assertEquals(2, cache.getCacheStatistics().getObjectCount());
1003: assertEquals(2, cache.getCacheStatistics().getObjectCount());
1004: assertEquals(2, cache.getCacheStatistics().getObjectCount());
1005: cache.remove("key1");
1006: assertEquals(1, cache.getCacheStatistics().getObjectCount());
1007: assertEquals(1, cache.getCacheStatistics().getObjectCount());
1008: assertEquals(1, cache.getCacheStatistics().getObjectCount());
1009: assertEquals(1, cache.getCacheStatistics().getObjectCount());
1010: assertEquals(1, cache.getCacheStatistics().getObjectCount());
1011: cache.remove("key2");
1012: assertEquals(0, cache.getCacheStatistics().getObjectCount());
1013: assertEquals(0, cache.getCacheStatistics().getObjectCount());
1014: assertEquals(0, cache.getCacheStatistics().getObjectCount());
1015: assertEquals(0, cache.getCacheStatistics().getObjectCount());
1016: assertEquals(0, cache.getCacheStatistics().getObjectCount());
1017: }
1018:
1019: /**
1020: * Checks the expense of checking for duplicates
1021: * JSR107 has only one keyset command. It returns a Set rather than a list, so
1022: * duplicates are automatically handled.
1023: * <p/>
1024: * 31ms for 2000 keys, half in memory and half on disk
1025: * <p/>
1026: */
1027: public void testGetKeysPerformance() throws Exception {
1028: Cache cache = getTest2Cache();
1029:
1030: for (int i = 0; i < 2000; i++) {
1031: cache.put("key" + i, "value");
1032: }
1033: //Add some duplicates
1034: cache.put("key0", "value");
1035: cache.put("key1", "value");
1036: cache.put("key2", "value");
1037: cache.put("key3", "value");
1038: cache.put("key4", "value");
1039: //let the spool be written
1040: Thread.sleep(1000);
1041: StopWatch stopWatch = new StopWatch();
1042: Set keys = cache.keySet();
1043: assertTrue("Should be 2000 keys. ", keys.size() == 2000);
1044: long getKeysTime = stopWatch.getElapsedTime();
1045:
1046: LOG.info("Time to get 2000 keys: With Duplicate Check: "
1047: + getKeysTime);
1048: assertTrue("Getting keys took more than 200ms: " + getKeysTime,
1049: getKeysTime < 100);
1050: }
1051:
1052: /**
1053: * Checks the expense of checking in-memory size
1054: * 3467890 bytes in 1601ms for JDK1.4.2
1055: * N/A to jsr107
1056: */
1057: // public void testCalculateInMemorySizePerformanceAndReasonableness() throws Exception {
1058:
1059: /**
1060: * Expire elements and verify size is correct.
1061: */
1062: public void testGetSizeAfterExpiry() throws Exception {
1063: //Set size so the second element overflows to disk.
1064: Cache cache = getTest2Cache();
1065: cache.put("key1", "value1");
1066: cache.put("key2", "value1");
1067:
1068: //Let the idle expire
1069: Thread.sleep(1020);
1070: assertEquals(null, cache.get("key1"));
1071: assertEquals(null, cache.get("key2"));
1072:
1073: assertEquals(0, cache.getCacheStatistics().getObjectCount());
1074: }
1075:
1076: /**
1077: * Tests initialisation failures
1078: * jsr107 has no lifecycle management
1079: */
1080: // public void testInitialiseFailures() {
1081:
1082: /**
1083: * Tests putting nulls throws correct exception
1084: *
1085: * @throws Exception
1086: */
1087: public void testNullTreatment() throws Exception {
1088: Ehcache ehcache = new net.sf.ehcache.Cache("testNullTreatment",
1089: 1, false, false, 5, 1);
1090: manager.addCache(ehcache);
1091: Cache cache = new JCache(ehcache, null);
1092:
1093: try {
1094: cache.put(null, null);
1095: assertNull(cache.get(null));
1096: cache.put(null, "value");
1097: assertEquals("value", cache.get(null));
1098: cache.put("key", null);
1099: assertEquals(null, cache.get("key"));
1100: assertFalse(null instanceof Serializable);
1101: } catch (Exception e) {
1102: fail("Should not have thrown an Execption");
1103: }
1104: }
1105:
1106: /**
1107: * Tests cache, memory store and disk store sizes from config
1108: * jsr107 does not breakdowns of store sizes.
1109: */
1110: public void testSizes() throws Exception {
1111: Cache cache = getTest1Cache();
1112: assertEquals(0, cache.getCacheStatistics().getObjectCount());
1113:
1114: for (int i = 0; i < 10010; i++) {
1115: cache.put("key" + i, "value1");
1116: }
1117: assertEquals(10010, cache.getCacheStatistics().getObjectCount());
1118:
1119: //NonSerializable
1120: cache.put(new Object(), Object.class);
1121:
1122: assertEquals(10011, cache.getCacheStatistics().getObjectCount());
1123:
1124: cache.remove("key4");
1125: cache.remove("key3");
1126:
1127: assertEquals(10009, cache.getCacheStatistics().getObjectCount());
1128:
1129: cache.clear();
1130: assertEquals(0, cache.getCacheStatistics().getObjectCount());
1131:
1132: }
1133:
1134: /**
1135: * Tests flushing the cache
1136: * jsr107 does not specify a disk store and therefore does not have a flush.
1137: */
1138: // public void testFlushWhenOverflowToDisk() throws Exception {
1139: /**
1140: * Tests put works correctly for Elements with overriden TTL
1141: * jsr107 does not support overriding TTL on a per entry basis
1142: *
1143: */
1144: // public void testPutWithOverriddenTTLAndTTI() throws Exception {
1145:
1146: /**
1147: * Tests using elements with null values. They should work as normal.
1148: *
1149: * @throws Exception
1150: */
1151: public void testNonSerializableElement() throws Exception {
1152: Ehcache ehcache = new net.sf.ehcache.Cache(
1153: "testElementWithNonSerializableValue", 1, true, false,
1154: 100, 200);
1155: manager.addCache(ehcache);
1156: Cache cache = new JCache(ehcache, null);
1157:
1158: cache.put("key1", new Object());
1159: cache.put("key2", new Object());
1160:
1161: //Removed because could not overflow
1162: assertNull(cache.get("key1"));
1163:
1164: //Second one should be in the MemoryStore and retrievable
1165: assertNotNull(cache.get("key2"));
1166: }
1167:
1168: /**
1169: * Tests what happens when an Element throws an Error on serialization. This mimics
1170: * what a nasty error like OutOfMemoryError could do.
1171: * <p/>
1172: * Before a change to the SpoolAndExpiryThread to handle this situation this test failed and generated
1173: * the following log message.
1174: * Jun 28, 2006 7:17:16 PM net.sf.ehcache.store.DiskStore put
1175: * SEVERE: testThreadKillerCache: Elements cannot be written to disk store because the spool thread has died.
1176: *
1177: * @throws Exception
1178: */
1179: public void testSpoolThreadHandlesThreadKiller() throws Exception {
1180: Ehcache ehcache = new net.sf.ehcache.Cache("testThreadKiller",
1181: 1, true, false, 100, 200);
1182: manager.addCache(ehcache);
1183: Cache cache = new JCache(ehcache, null);
1184:
1185: cache.put("key", new ThreadKiller());
1186: cache.put("key1", "one");
1187: cache.put("key2", "two");
1188:
1189: Thread.sleep(2000);
1190:
1191: assertNotNull(cache.get("key1"));
1192: assertNotNull(cache.get("key2"));
1193: }
1194:
1195: /**
1196: * Tests disk store and memory store size
1197: * jsr107 does not support getting store sizes
1198: */
1199: // public void testGetDiskStoreSize() throws Exception {
1200: /**
1201: * Tests that attempting to clone a cache fails with the right exception.
1202: * jsr107 does not make clone available
1203: *
1204: */
1205: // public void testCloneFailures() throws Exception {
1206:
1207: /**
1208: * Tests that the toString() method works.
1209: */
1210: public void testToString() throws CacheException {
1211: Cache cache = getTest2Cache();
1212: cache.clear();
1213: LOG.info(cache);
1214: assertTrue(cache.toString().indexOf("test2") > -1);
1215: assertTrue(380 < cache.toString().length());
1216: }
1217:
1218: /**
1219: * When does equals mean the same thing as == for an element?
1220: * NA JSR107 does not have elements
1221: */
1222: // public void testEquals() throws CacheException, InterruptedException {
1223: /**
1224: * Tests the uniqueness of the GUID
1225: * Not part of jsr107
1226: */
1227: // public void testGuid() {
1228: /**
1229: * Does the Object API work?
1230: * jsr107 is an object API
1231: */
1232: public void testAPIObjectCompatibility() throws CacheException {
1233: Cache cache = getTest1Cache();
1234:
1235: Object objectKey = new Object();
1236: Object objectValue = new Object();
1237:
1238: cache.put(objectKey, objectValue);
1239:
1240: //Cannot get it back using get
1241: Object retrievedElement = cache.get(objectKey);
1242: assertNotNull(retrievedElement);
1243:
1244: //Test that equals works
1245: assertEquals(objectValue, retrievedElement);
1246:
1247: }
1248:
1249: /**
1250: * Does the Serializable API work?
1251: */
1252: public void testAPISerializableCompatibility()
1253: throws CacheException {
1254: //Set size so the second element overflows to disk.
1255: Cache cache = getTest2Cache();
1256:
1257: //Try object compatibility
1258: Serializable key = new String("key");
1259: Serializable serializableValue = new String("retrievedValue");
1260: cache.put(key, serializableValue);
1261: cache.put("key2", serializableValue);
1262: Object retrievedValue = cache.get(key);
1263: assertEquals(serializableValue, retrievedValue);
1264: }
1265:
1266: /**
1267: * Test issues reported. N/A
1268: */
1269: // public void testDiskStoreFlorian() {
1270:
1271: /**
1272: * Multi-thread read-write test with lots of threads
1273: * Just use MemoryStore to put max stress on cache
1274: * Values that work:
1275: * <p/>
1276: * The get here will often load data, so it does not give raw cache performance. See the similar test in CacheTest
1277: * for that.
1278: */
1279: public void testReadWriteThreads() throws Exception {
1280:
1281: final int size = 10000;
1282: final int maxTime = (int) (1000 * StopWatch
1283: .getSpeedAdjustmentFactor());
1284: final JCache cache = getTest1Cache();
1285:
1286: CountingCacheLoader countingCacheLoader = (CountingCacheLoader) cache
1287: .getCacheLoader();
1288:
1289: long start = System.currentTimeMillis();
1290: final List executables = new ArrayList();
1291: final Random random = new Random();
1292:
1293: for (int i = 0; i < size; i++) {
1294: cache.put("" + i, "value");
1295: }
1296:
1297: // 50% of the time get data
1298: for (int i = 0; i < 26; i++) {
1299: final Executable executable = new Executable() {
1300: public void execute() throws Exception {
1301: final StopWatch stopWatch = new StopWatch();
1302: long start = stopWatch.getElapsedTime();
1303: cache.get("key" + random.nextInt(size));
1304: long end = stopWatch.getElapsedTime();
1305: long elapsed = end - start;
1306: assertTrue("Get time outside of allowed range: "
1307: + elapsed, elapsed < maxTime);
1308: }
1309: };
1310: executables.add(executable);
1311: }
1312:
1313: //25% of the time add data
1314: for (int i = 0; i < 10; i++) {
1315: final Executable executable = new Executable() {
1316: public void execute() throws Exception {
1317: final StopWatch stopWatch = new StopWatch();
1318: long start = stopWatch.getElapsedTime();
1319: cache.put("key" + random.nextInt(size), "value");
1320: long end = stopWatch.getElapsedTime();
1321: long elapsed = end - start;
1322: assertTrue("Put time outside of allowed range: "
1323: + elapsed, elapsed < maxTime);
1324: }
1325: };
1326: executables.add(executable);
1327: }
1328:
1329: //25% of the time remove the data
1330: for (int i = 0; i < 10; i++) {
1331: final Executable executable = new Executable() {
1332: public void execute() throws Exception {
1333: final StopWatch stopWatch = new StopWatch();
1334: long start = stopWatch.getElapsedTime();
1335: cache.remove("key" + random.nextInt(size));
1336: long end = stopWatch.getElapsedTime();
1337: long elapsed = end - start;
1338: assertTrue("Remove time outside of allowed range: "
1339: + elapsed, elapsed < maxTime);
1340: }
1341: };
1342: executables.add(executable);
1343: }
1344:
1345: //some of the time clear the data
1346: for (int i = 0; i < 10; i++) {
1347: final Executable executable = new Executable() {
1348: public void execute() throws Exception {
1349: final StopWatch stopWatch = new StopWatch();
1350: long start = stopWatch.getElapsedTime();
1351: int randomInteger = random.nextInt(20);
1352: if (randomInteger == 3) {
1353: cache.clear();
1354: }
1355: long end = stopWatch.getElapsedTime();
1356: long elapsed = end - start;
1357: assertTrue(
1358: "RemoveAll time outside of allowed range: "
1359: + elapsed, elapsed < maxTime);
1360: }
1361: };
1362: executables.add(executable);
1363: }
1364:
1365: //some of the time exercise the loaders through their various methods. Loader methods themselves make no performance
1366: //guarantees. They should only lock the cache when doing puts and gets, which the time limits on the other threads
1367: //will check for.
1368: for (int i = 0; i < 4; i++) {
1369: final Executable executable = new Executable() {
1370: public void execute() throws Exception {
1371: int randomInteger = random.nextInt(20);
1372: List keys = new ArrayList();
1373: for (int i = 0; i < 2; i++) {
1374: keys.add("key" + random.nextInt(size));
1375: }
1376: if (randomInteger == 1) {
1377: cache.load("key" + random.nextInt(size));
1378: }
1379: if (randomInteger == 2) {
1380: cache.loadAll(keys, null);
1381: }
1382: //JCache delegates to ehcache's getWithLoader so the get tests above do this already
1383: if (randomInteger == 4) {
1384: cache.getAll(keys, null);
1385: }
1386: }
1387: };
1388: executables.add(executable);
1389: }
1390:
1391: runThreads(executables);
1392: long end = System.currentTimeMillis();
1393: LOG.info("Total time for the test: " + (end - start) + " ms");
1394: LOG
1395: .info("Total loads: "
1396: + countingCacheLoader.getLoadCounter());
1397: LOG.info("Total loadAlls: "
1398: + countingCacheLoader.getLoadAllCounter());
1399: }
1400:
1401: /**
1402: * Tests the public API load method with a single item
1403: */
1404: public void testLoad() throws InterruptedException,
1405: ExecutionException, CacheException {
1406:
1407: CountingCacheLoader countingCacheLoader = new CountingCacheLoader();
1408: JCache jcache = new JCache(manager.getCache("sampleCache1"),
1409: countingCacheLoader);
1410: jcache.load("key1");
1411: Thread.sleep(500);
1412: assertEquals(1, jcache.size());
1413: assertEquals(1, countingCacheLoader.getLoadCounter());
1414: }
1415:
1416: /**
1417: * Tests that the setLoader method allows the loader to be changed. The load is async so timing is important.
1418: */
1419: public void testLoadWithDynamicLoaderInjection()
1420: throws InterruptedException, ExecutionException,
1421: CacheException {
1422:
1423: //null loader so no loading happens
1424: JCache jCache = new JCache(manager.getCache("sampleCache1"),
1425: null);
1426: jCache.setCacheLoader(null);
1427: assertEquals(0, jCache.size());
1428: jCache.load("key1");
1429: Thread.sleep(1000);
1430: assertEquals(0, jCache.size());
1431:
1432: CountingCacheLoader countingCacheLoader = new CountingCacheLoader();
1433: jCache.setCacheLoader(countingCacheLoader);
1434:
1435: jCache.load("key1");
1436: Thread.sleep(1000);
1437:
1438: assertEquals(1, jCache.size());
1439: assertEquals(1, countingCacheLoader.getLoadCounter());
1440: }
1441:
1442: /**
1443: * Test exception handling from JCache
1444: */
1445: public void testCacheExceptionHandler() {
1446: JCache jcache = manager.getJCache("exceptionHandlingCache");
1447:
1448: jcache.setCacheLoader(new ExceptionThrowingLoader());
1449:
1450: //throws an exception
1451: jcache.get("key");
1452:
1453: assertEquals(1, CountingExceptionHandler.HANDLED_EXCEPTIONS
1454: .size());
1455: assertEquals(
1456: "key",
1457: ((CountingExceptionHandler.HandledException) CountingExceptionHandler.HANDLED_EXCEPTIONS
1458: .get(0)).getKey());
1459: assertTrue((((CountingExceptionHandler.HandledException) CountingExceptionHandler.HANDLED_EXCEPTIONS
1460: .get(0)).getException()) instanceof RuntimeException);
1461: }
1462:
1463: /**
1464: * Tests the loadAll Public API method
1465: */
1466: public void testLoadAll() throws InterruptedException,
1467: ExecutionException, CacheException {
1468:
1469: CountingCacheLoader countingCacheLoader = new CountingCacheLoader();
1470: JCache jcache = new JCache(manager.getCache("sampleCache1"),
1471: countingCacheLoader);
1472:
1473: //check null works ok
1474: jcache.loadAll(null);
1475:
1476: List keys = new ArrayList();
1477: for (int i = 0; i < 999; i++) {
1478: keys.add(new Integer(i));
1479: }
1480: //make on key null
1481: keys.add(null);
1482:
1483: //pre populate only 1 element
1484: jcache.put(new Integer(1), "");
1485:
1486: jcache.loadAll(keys);
1487: Thread.sleep((long) (3000 * StopWatch
1488: .getSpeedAdjustmentFactor()));
1489:
1490: assertEquals(1000, jcache.size());
1491: assertEquals(999, countingCacheLoader.getLoadAllCounter());
1492:
1493: }
1494:
1495: /**
1496: * Tests the getAll Public API method
1497: */
1498: public void testGetAll() throws InterruptedException,
1499: ExecutionException, CacheException {
1500:
1501: JCache jcache = new JCache(manager.getCache("sampleCache1"),
1502: null);
1503:
1504: //check null CacheLoader
1505: Map map = jcache.getAll(null);
1506: assertNotNull(map);
1507: assertEquals(0, map.size());
1508:
1509: CountingCacheLoader countingCacheLoader = new CountingCacheLoader();
1510: jcache.setCacheLoader(countingCacheLoader);
1511:
1512: //check null
1513: map = jcache.getAll(null);
1514: assertNotNull(map);
1515: assertEquals(0, map.size());
1516:
1517: List keys = new ArrayList();
1518: for (int i = 0; i < 1000; i++) {
1519: keys.add(new Integer(i));
1520: }
1521:
1522: //pre populate only 1 element
1523: jcache.put(new Integer(1), "");
1524:
1525: Map result = jcache.getAll(keys);
1526: Object object = result.get(new Integer(1));
1527: //make sure we are not wrapping with Element.
1528: assertFalse(object instanceof Element);
1529:
1530: assertEquals(1000, jcache.size());
1531: assertEquals(999, countingCacheLoader.getLoadAllCounter());
1532:
1533: assertFalse(result.get(new Integer(1)) == null);
1534: assertFalse(result.get(new Integer(1)) instanceof Element);
1535: }
1536:
1537: }
|