简体   繁体   English

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

[英]java: is the function thread-safe in hashmap.put(key, function())?

I want to put a value returned from a function into ConcurrentHashmap like that 我想像这样将从函数返回的值放入ConcurrentHashmap中

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

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

public Object function() {
    return anyObject;
}

May I know the function (eg function()) is thread-safe or not? 我可以知道函数(例如function())是否是线程安全的吗? Please advise if there is any tutorial Thanks. 请告知是否有任何教程谢谢。

call itself in not thread-safe, only put operation atomic. 调用自身不是线程安全的,仅将操作原子化。

Instead you can use guava 相反,您可以使用番石榴

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);
         }
       });

Please notice makeComputingMap() call 请注意makeComputingMap()调用

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

You could use the Read / Write Locks in Java. 您可以在Java中使用读/写锁。

Example: 例:

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()
     }
   }
 }

Ref: 参考:

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 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM