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