1

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.

xavierz
  • 335
  • 1
  • 11
  • Are you familiar with http://www.ehcache.org/ ? – Tatu Lund Apr 19 '18 at 17:04
  • @TatuLund looks interesting. but there must be a way in Vaadin. don't wanna import a whole framework for this – xavierz Apr 19 '18 at 17:22
  • What kind of objects those are? Ehcache is good choice for database or rest backend caching. – Tatu Lund Apr 19 '18 at 17:56
  • @xavierz `but there must be a way in Vaadin` why should they reinvent the wheel? https://stackoverflow.com/questions/575685/looking-for-simple-java-in-memory-cache?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – André Schild Apr 19 '18 at 17:58
  • You could have a look at Caching with Spring: https://spring.io/guides/gs/caching/ – jstadler Apr 24 '18 at 21:15

1 Answers1

3

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);
    }
}