我正在单个服务器上实现乐观事务(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() {
现在我的问题是:Java 中是否有一个锁可以在需要时使用:
- 独立于获取锁的线程来释放锁。
- 拥有读锁和写锁(并且可能从读升级到写)
- 不等待(阻塞)锁(我只使用
tryLock
)?
最佳答案
StampedLock
对我来说很有效,并且可以从另一个线程解锁。我用它作为:
ReadWriteLock lock = new StampedLock().asReadWriteLock();
关于java - 不同线程释放的可重入ReadWriteLock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34019122/