开发者

Can/Should I use ConcurrentMap together with my own cache?

Many people refer ConcurrentMap as a cache.

Is it a good idea to do this:

public List<Task> listTasks(final ProcessDefinition def, final boolean filterEnumerated) {
    final String CACHENAME = def.getName() + "-v" + def.getVersion() + "-Tasks";
    ConcurrentMap<String, List<Task>> cache = (ConcurrentMap<String, List<Task>>) Contexts.getApplicationContext().get(CACHENAME);
    if (Contexts.getApplicationContext().isSet(CACHENAME) && cache != null) {
        return cache.get(CACHENAME);
    } else {

        ConcurrentMap<String, List<Task>> myTasks = new MapMaker()
           .softValues()
           .expiration(2L, TimeUnit.HOURS)
           .makeComputingMap(
               new Function<String, List<Task>>() {
                @Override
                public List<Task> apply(String from) {
                    return getTasksFromDefinition(def, filterEnumerated);
                }
               });

        myTasks.put(CACHENAME, getTasksFromDefinition(def, filterE开发者_开发百科numerated));

        Contexts.getApplicationContext().set(CACHENAME,myTasks);
        Collection<List<Task>> tz = myTasks.values();
        //First element in the collection
        return new ArrayList<Task>(tz.iterator().next());
    }
}

Or isn't it necessary to use the ApplicationContext (which is the java-ee application context) to also cache the map, and just retrieve the value from the map?

Similar to the answer on this post

Also I would like to know, the .expiration(2L, TimeUnit.HOURS). Is this really 2 hours, or does the long take values in milliseconds?


I personally think it's fine to store such a cache in your ApplicationContext as it is threadsafe. But do be aware of the size of the cache, especially if you are clustering etc.

On the expiration question, the expiration is 2 hours as you'd expect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜