代码之家  ›  专栏  ›  技术社区  ›  Shervin Asgari

我可以/应该将ConcurrentMap与我自己的缓存一起使用吗?

  •  1
  • Shervin Asgari  · 技术社区  · 14 年前

    许多人把ConcurrentMap称为缓存。

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

    或者不需要使用application context(这是java ee应用程序上下文)来缓存映射,并从映射中检索值吗?
    类似于这个问题的答案 post

    我也想知道 .expiration(2L, TimeUnit.HOURS) . 这真的是2个小时吗,还是long以毫秒为单位?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Martijn Verburg    14 年前

    我个人认为,在ApplicationContext中存储这样的缓存是可以的,因为它是线程安全的。但是一定要注意缓存的大小,特别是在集群等情况下。

    推荐文章