9

I am using JCache API to configure caches in my application that uses spring caching with Ehcache 3.

cacheManager.createCache("users", new MutableConfiguration<String, User>()
                    .setStoreByValue(false)
                    .setManagementEnabled(true)
                    .setStatisticsEnabled(true)
                    .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES)));

How can I limit cache size to say 50 entries? It is easy to do it via Ehcache XML configuration but if there is a way to control this using JCache config API I would prefer to use that.

abhijitab
  • 101
  • 1
  • 3

1 Answers1

11

Unfortunately, limiting the size is out of the scope of the standard. You need always a vendor specific configuration, to do that.

I am not happy about that myself and have use cases where I want to set the size limit inside the program and with a standard API. However, there are valid reasons leaving it out of the standard, too:

What does the size limit mean? Which are the exact semantics a cache needs to follow? Can useful semantics be defined for all caches? For example for a distributed cache it is very hard to determine the number of entries in the cache at all.

There are different concepts to limit the cache size. Some caches allow to set a byte size limit.

With non trivial applications you do not want to write the sizes in the code. The size is configuration and that should be somewhere separate and manageable. An external configuration is out of the scope of the standard, too. There are many opinions, and no standard way to do configuration.

cruftex
  • 5,545
  • 2
  • 20
  • 36
  • I have the same issue. In my case it is ehcache 3. How can I do the custom configuration? I only see that I can provide a MutableConfiguration . How do I get the custom ehcache settings into it? – Christian Schneider Jul 12 '21 at 15:39
  • @ChristianSchneider maybe that is a separate stack overflow question. But you find the answer directly in the EHCache documentation. – cruftex Jul 13 '21 at 16:22