Search code examples
javacache2k

Reloading all cache2k entries at once


I would like to reload all cache entries in cache2k at once. I'm using version 1.2.2.

I've tried to use org.cache2k.integration.CacheLoader#load method but it only accepts one key and returns one value. I don't like the idea to download only one record from the database at once. It's not optimal.

I expect to reload all cache entries using exactly one db query. Please guide what is the recommended way to achieve it.

Thank you for your answer!


Solution

  • You can instruct cache2k to reload all entries via:

      cache.reloadAll(cache.keys(), null);
    

    However, in the current version this reloads all entries one by one via the loader thread pool. So called "bulk loading" is missing at the moment. There is already some more demand for it. Its tracked here: https://github.com/cache2k/cache2k/issues/116

    In case you always load the whole contents in bulk, there is the question whether you actually need to have separate cache entries, and rather cache a single map containing all items. See some discussion here: https://github.com/cache2k/cache2k/issues/122

    Using a loader has several advantages, e.g. resilience and refresh ahead. If you don't needs this and just want to populate the cache with new contents you can use cache.keys() to get a list of the cached keys, request the database and then update the whole cache via cache.putAll().