java:hashmap.put(key,function())中的函数是否是线程安全的?

时间:2012-07-26 15:20:52

标签: java

我想将函数返回的值放入ConcurrentHashmap,就像那样

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

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

public Object function() {
    return anyObject;
}

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

2 个答案:

答案 0 :(得分:1)

调用自身不是线程安全的,只是把操作放在原子上。

相反,你可以使用番石榴

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

答案 1 :(得分:0)

您可以使用Java中的读/写锁。

示例:

class X {
  ReadWriteLock rw;

  public void read() throws InterruptedException { 
    rw.readLock().acquire();
    try {
      // ... do the read
    } finally {
      rw.readlock().release()
    }
 }

 public void write() throws InterruptedException { 
     rw.writeLock().acquire();
     try {
       // ... do the write
     } finally {
       rw.writelock().release()
     }
   }
 }

参考:

http://www.coderanch.com/t/232685/threads/java/Concurrent-access-HashMap http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReadWriteLock.html http://tutorials.jenkov.com/java-concurrency/read-write-locks.html