How to acquire a lock by a key

前端 未结 6 1373
一个人的身影
一个人的身影 2020-11-28 09:47

What is the best way to prevent concurrent update of one record in a key-value set without locking the entire set? Semantically, I\'m looking for some kind of locking by a k

6条回答
  •  鱼传尺愫
    2020-11-28 10:29

    private static final Set lockedKeys = new HashSet<>();
    
    private void lock(String key) throws InterruptedException {
        synchronized (lockedKeys) {
            while (!lockedKeys.add(key)) {
                lockedKeys.wait();
            }
        }
    }
    
    private void unlock(String key) {
        synchronized (lockedKeys) {
            lockedKeys.remove(key);
            lockedKeys.notifyAll();
        }
    }
    
    public void doSynchronously(String key) throws InterruptedException {
        try {
            lock(key);
    
            //Do what you need with your key.
            //For different keys this part is executed in parallel.
            //For equal keys this part is executed synchronously.
    
        } finally {
            unlock(key);
        }
    }
    

    try-finally - is very important - you must guarantee to unlock waiting threads after your operation even if your operation threw exception.

提交回复
热议问题