TimedCache { public boolean update(K key) { Long curr = new Long(System.currentTimeMillis()); Long prev = cache.putIfAbsent(key, curr); if (prev == null) { return false; } if (curr - prev > this.timeoutInterval) { if (cache.replace(key, prev, curr)) { return false; } } return true; } TimedCache(int capacity, int timeToLive); long getTimeoutInterval(); boolean update(K key);  }
@Test public void testCaching() throws InterruptedException { int timeout = 50; int timeToSleep = 60; cache = new TimedCache<TimedCacheTest.CacheEntry>(100, timeout); CacheEntry e1a = new CacheEntry(1); CacheEntry e1b = new CacheEntry(1); CacheEntry e1c = new CacheEntry(1); CacheEntry e2 = new CacheEntry(2); assertEquals(false, cache.update(e1a)); assertEquals(true, cache.update(e1a)); assertEquals(true, cache.update(e1b)); assertEquals(true, cache.update(e1c)); assertEquals(false, cache.update(e2)); assertEquals(true, cache.update(e2)); Thread.sleep(timeToSleep); assertEquals(false, cache.update(e1a)); assertEquals(false, cache.update(e2)); }
@Test public void testCapacity() throws InterruptedException { int timeout = 5000; cache = new TimedCache<TimedCacheTest.CacheEntry>(2, timeout); CacheEntry e1 = new CacheEntry(1); for (int i=0; i < 100; i++) { CacheEntry e = new CacheEntry(i); cache.update(e); } assertEquals(false, cache.update(e1)); }