【问题标题】:Is trere a simplier way to have concurrentmap with locks?有没有更简单的方法来使用锁并发映射?
【发布时间】:2016-03-11 16:12:10
【问题描述】:

我需要在每个实体 ID 的某些功能中锁定。

private final ConcurrentMap<Long, Lock> idLocks = Maps.newConcurrentMap();

public void doSmth(Long id){
    ReentrantLock newLock = new ReentrantLock();
    Lock lock = prLocks.putIfAbsent( id, newLock ); //returns null for first run for this id
    if (null == lock) { //have to do null checking 
        lock = newLock;
    }
    if (lock.tryLock()){
        try {
        //some code here
        } finally {
            lock.unlock();
        }
    }
}

有没有办法运行Lock lock = returnExistingOrPutAndReturnNew( id, newLock ); 来摆脱空值检查?

【问题讨论】:

    标签: java concurrency java.util.concurrent


    【解决方案1】:

    不,ConcurrentMap中没有这种方法,但是可以使用guava LoadingCache

    private final LoadingCache<Long, Lock> idLocks = CacheBuilder.newBuilder()
           .build(
                 new CacheLoader<Long, Lock>() {
                       public Lock load(Long id) throws AnyException {
                           return new ReentrantLock();
                       }
                 });
    
    public void doSmth(Long id){
         Lock lock = prLocks.get(id); //always return not-null Lock
         if (lock.tryLock()){
              try {
                 //some code here
              } finally {
                 lock.unlock();
              }
         }
     }
    

    更新:

    在 java 8 中你可以使用Map#computeIfAbsent 方法:

    public void doSmth(Long id){
        Lock lock = prLocks.computeIfAbsent(id, key -> new ReentrantLock());
        if (lock.tryLock()){
            try {
                //some code here
            } finally {
                lock.unlock();
            }
        }
    }
    
    猜你喜欢
    • 2017-12-18
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    相关资源
    最近更新 更多