Search in sources :

Example 1 with EvictionCallback

use of org.apache.jackrabbit.oak.cache.CacheLIRS.EvictionCallback in project jackrabbit-oak by apache.

the class CacheTest method evictionCallbackRandomized.

@Test
public void evictionCallbackRandomized() throws ExecutionException {
    final HashMap<Integer, Integer> evictedMap = new HashMap<Integer, Integer>();
    final HashSet<Integer> evictedNonResidentSet = new HashSet<Integer>();
    CacheLIRS<Integer, Integer> cache = CacheLIRS.<Integer, Integer>newBuilder().maximumSize(10).evictionCallback(new EvictionCallback<Integer, Integer>() {

        @Override
        public void evicted(Integer key, Integer value, RemovalCause cause) {
            if (value == null) {
                assertTrue(evictedNonResidentSet.add(key));
            } else {
                assertEquals(null, evictedMap.put(key, value));
            }
        }
    }).build();
    Random r = new Random(1);
    for (int k = 0; k < 10000; k++) {
        if (r.nextInt(20) == 0) {
            evictedMap.clear();
            evictedNonResidentSet.clear();
            long size = cache.size();
            long sizeNonResident = cache.sizeNonResident();
            cache.invalidateAll();
            assertEquals(evictedMap.size(), size);
            assertEquals(evictedNonResidentSet.size(), sizeNonResident);
        }
        evictedMap.clear();
        evictedNonResidentSet.clear();
        int key = r.nextInt(20);
        if (r.nextBoolean()) {
            cache.put(key, k);
        } else {
            cache.get(key);
        }
        for (Entry<Integer, Integer> ev : evictedMap.entrySet()) {
            int ek = ev.getKey();
            if (ek == key) {
            // the same key was inserted just now
            } else {
                assertFalse(cache.containsKey(ek));
            }
        }
        for (Entry<Integer, Integer> ev : evictedMap.entrySet()) {
            int ek = ev.getKey();
            Integer v = ev.getValue();
            // an old value
            assertTrue(v < k);
            if (ek == key) {
            // the same key was inserted just now
            } else {
                assertFalse(cache.containsKey(ek));
            }
        }
    }
}
Also used : Random(java.util.Random) HashMap(java.util.HashMap) EvictionCallback(org.apache.jackrabbit.oak.cache.CacheLIRS.EvictionCallback) RemovalCause(com.google.common.cache.RemovalCause) HashSet(java.util.HashSet) Sets.newHashSet(com.google.common.collect.Sets.newHashSet) Test(org.junit.Test)

Aggregations

RemovalCause (com.google.common.cache.RemovalCause)1 Sets.newHashSet (com.google.common.collect.Sets.newHashSet)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Random (java.util.Random)1 EvictionCallback (org.apache.jackrabbit.oak.cache.CacheLIRS.EvictionCallback)1 Test (org.junit.Test)1