我想像这样将从函数返回的值放入ConcurrentHashmap中

private static ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<String, Object>();

public void process() {
    map.put(key, function());
}

public Object function() {
    return anyObject;
}


我可以知道函数(例如function())是否是线程安全的吗?
请告知是否有任何教程
谢谢。

最佳答案

调用自身不是线程安全的,仅将操作原子化。

相反,您可以使用番石榴

ConcurrentMap<Key, Graph> graphs = new MapMaker()
   .concurrencyLevel(4)
   .weakKeys()
   .maximumSize(10000)
   .expireAfterWrite(10, TimeUnit.MINUTES)
   .makeComputingMap(
       new Function<Key, Graph>() {
         public Graph apply(Key key) {
           return createExpensiveGraph(key);
         }
       });


请注意makeComputingMap()调用

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/MapMaker.html

09-10 07:57
查看更多