Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EHCache 3.5 Get All Cache Keys / Entries

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

like image 553
robjwilkins Avatar asked May 16 '18 10:05

robjwilkins


People also ask

Is EhCache cache thread safe?

It is inherently not thread-safe to modify the value. It is safer to retrieve a value, delete the cache element, and then reinsert the value.

Is EhCache local cache?

The cache acts as a local copy of data retrieved from or stored to the system-of-record. This is often a traditional database, although it might be a specialized file system or some other reliable long-term storage. For the purposes of using Ehcache, the SOR is assumed to be a database.

How does EhCache store data?

Data stores supported by Ehcache include: On-Heap Store - Utilizes Java's on-heap RAM memory to store cache entries. This tier utilizes the same heap memory as your Java application, all of which must be scanned by the JVM garbage collector.

How do I access EhCache?

It can be accessed via a simple web UI, as well as a scriptable API. In this way, it is easy to integrate with common third party systems management tools (such as Hyperic, Nagios etc). The probe is designed to be compatible with all versions of Ehcache from 1.5 and requires JDK 1.6.


2 Answers

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.

like image 160
Louis Jacomet Avatar answered Sep 21 '22 19:09

Louis Jacomet


Why not something like this?

Map<String, Foo> foos = StreamSupport.stream(cache.spliterator(), false)
  .collect(Collectors.toMap(Cache.Entry::getKey, Cache.Entry::getValue));

or

List<Cache.Entry<String, Foo>> foos = StreamSupport.stream(cache.spliterator(), false)
  .collect(Collectors.toList());

or (old style)

List<Cache.Entry<String, Foo>> foos = new ArrayList<>();
for(Cache.Entry<String, Foo> entry : cache) {
  foos.add(entry);
}
like image 37
Henri Avatar answered Sep 18 '22 19:09

Henri