Search code examples
javaspringcachingconcurrenthashmaplinkedhashmap

How to get evicted value from org.apache.cayenne.util.concurrentlinkedhashmap?


I am using org.apache.cayenne.util.concurrentlinkedhashmap and setting cache capacity by using maximumWeightedCpacity(3000) method once cache reached to its threshold limit it starts evicting the old entries. I need that entries which is getting evicted. How Can I get those entries using listener?


Solution

  • That is an embedded copy of the ConcurrentLinkedHashMap library. The tutorial provides an example using an EvictionListener and can be written as,

    ConcurrentMap<K, V> cache = new ConcurrentLinkedHashMap.Builder<K, V>()
        .maximumWeightedCapacity(3_000)
        .listener((key, value) ->
            System.out.printf("Evicted key=%s, value=%s%n", key, value))
        .build();
    

    While this library is small and nibble, it was written in the Java 5 timeframe. It is still excellent for embedded cases to minimize the jar size, but general purpose usages should prefer Caffeine instead. That library provides a richer feature set and additional performance improvements.

    Cache<K, V> graphs = Caffeine.newBuilder()
        .maximumSize(3_000)
        .removalListener((K key, V value, RemovalCause cause) ->
            System.out.printf("%s: key=%s, value=%s%n", cause, key, value))
        .build();