java - 不同线程释放的可重入ReadWriteLock

标签 java multithreading concurrency transactions locking

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

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

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

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

    /**
     * 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() {

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

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

最佳答案

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

ReadWriteLock lock = new StampedLock().asReadWriteLock();

关于java - 不同线程释放的可重入ReadWriteLock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34019122/

相关文章:

java - 接口(interface) : profit of using

java file.delete() 返回 false 但 file.exists() 返回 true

java - 正则表达式在 for 循环中查找 DAO

python - 在多线程生产者-消费者模式下,如何让工作线程在工作完成后退出?

java - 如何停止或销毁 Android 线程

Java,制作一个一次只能调用一次的方法

OOP 和可扩展性

java - 如何从 Java 中的对象 vector 获取特定类型的对象

Java 文件复制 - 将同一文件并行复制到 10/20 USB 设备

java - java的内在对象锁有一个单独的关联条件对象是什么意思