Search code examples
springcachingehcache

Can Spring @Cacheable be configured to block on a cache miss?


Can the Spring @Cacheable be configure so that if there is a cache miss calls to the cacheable method get blocked until the cacheable method executes once and the cache is populated?

In my case I am dealing with data from the db that does not change often in fact if this data changes then the app will need to be restarted. I can create @PostConstruct methods and init the data as each service is launching but that does not seem as "elegant" as the @Cacheable annotation.

I am planning to use EhCache with the Spring @Cacheable annotation.

update:

Here are some issues that I ran into in trying to use @PostConstruct, in case some one else run into those issues. @PostConstruct methods can't be @Transactional because they run after the properties of the object are set and not after the whole spring context is configured. So you can't assume that the TX manager is all setup and configured by the time @PostConstruct method is called. The workaround for this is to implement a ApplicationListener and inject a TransactionTemplate manually ... etc a lot of extra work that is simplified by using @Cacheable.


Solution

  • I don't think @PostConstruct is inelegant, seems perfect solution to me. You want the method(s) called only when app is restarted. What could be better ?

    But you can also do this to block calls until a cache is available

    @Cacheable(cacheName="yourCache", decoratedCacheType= DecoratedCacheType.SELF_POPULATING_CACHE)
    public List<String> getWhatever(int id) {
    //call database
    }
    

    and to make the cache autorefresh this :

    @Cacheable(cacheName="yourCache", refreshInterval=1000, decoratedCacheType= DecoratedCacheType.REFRESHING_SELF_POPULATING_CACHE)
    public List<String> getWhatever(int id) {
      //call database
    }
    

    kudos