0

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

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

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

public Object function() {
    return anyObject;
}

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

4

2 回答 2

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

于 2012-07-26T15:23:15.683 回答
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

于 2012-07-26T16:01:31.157 回答