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
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.
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.
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With