EHCache 3.5 Get All Cache Keys / Entries

robjwilkins picture robjwilkins · May 16, 2018 · Viewed 8.7k times · Source

I'm using EHCache 3.5.2 and having trouble getting all cache keys and cache entries.

I am using the CacheManager to create a cache. I'm then populating it with some data. I'd then like to retrieve all entries in the cache.

Some sample code:

Cache<String, Foo> cache = cacheManager.createCache("fooCache",
     CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, Foo.class,
         ResourcePoolsBuilder.heap(20)).build());

cache.putAll(repository.findAll().stream().collect(toMap(Foo::getId, foo -> foo)));

List<Foo> foos = cache.???
List<String> keys = cache.???

Is this possible with v3.5? It seems it was possible in older versions of EHCache.

thanks

Answer

Louis Jacomet picture Louis Jacomet · May 17, 2018

By design, this is not a simple API call in Ehcache. Because of the tiering model it supports, realising all keys or values on heap could cause the JVM to run out of memory.

As shown by the other answers, there are ways to achieve this.

But it is considered a caching anti-pattern to have to get the whole content of the cache at once.