I'm having some concurrency issues with my web application, where there is a write to the DB that is done, and there may also be simultaneous reads. The write first deletes all the rows and then inserts new ones, so there is the chance that the reads will be done while the database is empty, resulting in an error. I'm using the ReentrantReadWriteLock, but want to make sure that I'm using it correctly. Any fixes would be appreciated.
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();
}
}
As far as the question is concerned: your usage of ReentrantReadWriteLock
is correct.
With regard to your problem: I think you need to look toward the transaction isolation level in effect (and possibly adjust it).
Hope this helps...
Isolation levels explanation in another SO thread: what is difference between non-repeatable read and phantom read?
Java tutorial chapter on isolation levels: http://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html#transactions_data_integrity