gpt4 book ai didi

Java ReentrantReadWriteLock - 正确用法?

转载 作者:太空宇宙 更新时间:2023-11-04 06:47:29 26 4
gpt4 key购买 nike

我的 Web 应用程序遇到一些并发问题,其中已完成对数据库的写入,并且可能还存在同时读取。写入时会先删除所有行,然后插入新行,因此有可能在数据库为空时进行读取,从而导致错误。我正在使用 ReentrantReadWriteLock,但想确保我正确使用它。如有任何修复,我们将不胜感激。

private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

public static Schedule lookupSchedule()
{
lock.readLock().lock();
try
{
// read data from the database, manipulate it, return it
}
finally
{
lock.readLock().unlock();
}
}

public static void setSchedule()
{
Connection conn = DB.getConnection();
lock.writeLock.lock();
try
{
conn.openTransaction();
// delete all the rows from the table
// insert all the new rows into the table
conn.committTransaction();
}
catch (Exception ex)
{
conn.rollbackTransaction();
}
finally
{
lock.writeLock.unlock();
}
}

最佳答案

就问题而言:您对 ReentrantReadWriteLock 的使用是正确的。

关于您的问题:我认为您需要查看有效的事务隔离级别(并可能对其进行调整)。

希望这有帮助...

另一个SO线程中的隔离级别解释:what is difference between non-repeatable read and phantom read?

关于隔离级别的 Java 教程章节:http://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html#transactions_data_integrity

关于Java ReentrantReadWriteLock - 正确用法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23786130/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com