我的 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();
}
}