LRURegion implements CacheRegion<Long, T> { @Override public long reduceBy(long reduceSize) { long initialMemory = memorySize(); LOG.debug("initial memory: {}", initialMemory); long targetMemory = initialMemory - reduceSize; targetMemory = targetMemory > 0 ? targetMemory : 0; LOG.debug("Target memory: {}", targetMemory); Set<Long> checkedKeys = new HashSet<>(); while(memorySize() > targetMemory) { Long key = blockAccessTime.first(); if(!checkedKeys.contains(key)) { LOG.debug("Removing key: {}", key); removeEntry(key); checkedKeys.add(key); } else { LOG.debug("Cannot reduce memory footprint of region: {} further, key: {} cannot be found", this, key); break; } } long afterSize = memorySize(); LOG.debug("After size: {}", afterSize); return initialMemory - memorySize(); } LRURegion(String name); @Override long lastRegionAccess(); @Override String name(); @Override long memorySize(); @Override long reduceBy(long reduceSize); @Override T putEntry(Long key, T entry); @Override boolean contains(Long key); @Override T getEntry(Long key); @Override boolean removeEntry(Long key); @Override Collection<T> values(); @Override int size(); @Override void clear(); @Override String toString();  }
@Test public void testReduceBy() { int testSize = 100000; long blockSize = 9999; LRURegion<MockCacheEntry<Long>> region = new LRURegion<>("region"); for(int i=0; i<testSize; i++) { region.putEntry((long)i, new MockCacheEntry<>(blockSize, (long)i * 2)); } region.reduceBy(10 * blockSize); assertThat(region.size(), is(testSize - 10)); assertThat(region.memorySize(), is((testSize - 10) * blockSize)); }