Search code examples
javacachingvaadinheap-memoryvaadin8

Vaadin 8 - application-wide cache


In my Vaadin 8 project, there are some objects that I keep in the main memory whenever the application is up&running.

For memory efficiency, I'm looking to keep this cache for all users-- not a separate cache for each user. So the cache should be per application, i.e., a single set of these objects, and NOT per session.

How to do this in Vaadin 8? Please note - there's no Spring in this system, so doing it on Spring is not an option.

Excuse if a naïve question. Not yet that savvy on Vaadin/web dev.


Solution

  • For a application wide cache, just create a class with a public static cache that you can access from everywhere. The static object will be the same for every UI and session.

    Since you didn't specify what do you want to cache, I suppose you want to cache custom objects made by you to use for some sort of server side logic.

    To do so in plain java, you can create a simple hashmap to use as cache. A VERY simple example would be:

    public class GlobalCache {
    
        private static ConcurrentHashMap<String, Object> cacheMap = new ConcurrentHashMap<>();
    
        public static Object getObject(String key, Function<String, Object> creator) {
            return cacheMap.computeIfAbsent(key, creator);
        }
    
    }
    

    That wouldn't be a good cache since it won't invalidate its entries. If you can add any libraries, you should add Guava. Guava provides a great cache implementation that you can use:

    //Add this to your gradle:
    dependencies {
        implementation group: 'com.google.guava', name: 'guava', version: '24.1-jre'
    }
    
    //And this will become your code
    public class GlobalCache {
        private static Cache<String, Object> cache = 
            CacheBuilder.newBuilder().maximumSize(100).expireAfterWrite(5, TimeUnit.MINUTES).build();
    
        public static Object getObject(String key, Callable<? extends Object> creator) throws ExecutionException {
            return cache.get(key, creator);
        }
    }