不同线程释放的可重入ReadWriteLock

Eri*_*rik 1 java concurrency multithreading locking transactions

我正在单个服务器上实现乐观事务(BOCC)。在提交时,根据当前数据库状态验证读取和写入集(如果自读取后状态发生更改,则事务将中止)。如果验证成功,所有对象都会写入数据库。

对不同对象集的验证(加上数据库更新)可以是并发的,但必须使用读锁和写锁来保护重叠的对象集。

我使用ReentrantReadWriteLock来确保验证的安全,效果很好。现在我正在编写一个恢复机制,如果由于某些错误(验证后)并非所有对象都写入数据库,该机制会重复更新过程。

因此恢复会重复数据库写入,然后尝试释放锁(恢复成功后)。问题是我尝试从不同的线程释放锁(因为恢复是由另一个后台服务执行的),这会抛出IllegalMonitorStateException. 该方法的注释unlock验证了此行为。

    /**
     * Attempts to release this lock.
     *
     * <p>If the current thread is the holder of this lock then
     * the hold count is decremented. If the hold count is now
     * zero then the lock is released.  If the current thread is
     * not the holder of this lock then {@link
     * IllegalMonitorStateException} is thrown.
     *
     * @throws IllegalMonitorStateException if the current thread does not
     * hold this lock
     */
    public void unlock() {
Run Code Online (Sandbox Code Playgroud)

现在我的问题是:如果我需要的话,Java 中是否有一个可以使用的锁:

  • 独立于获取锁的线程来释放锁。
  • 拥有读锁和写锁(并且可能从读升级到写)
  • 不等待(阻止)锁(我只使用tryLock)?

Eri*_*rik 5

StampedLock对我来说很有效,并且可以从另一个线程解锁。我用它作为:

ReadWriteLock lock = new StampedLock().asReadWriteLock();
Run Code Online (Sandbox Code Playgroud)