I think using a read-write lock is enough in most cases.
Suppose you have written the following,
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class MyDatabase extends SQLiteOpenHelper
{
private static final ReadWriteLock rwLock = new ReentrantReadWriteLock(true);
private static void beginReadLock()
{
rwLock.readLock().lock();
}
private static void endReadLock()
{
rwLock.readLock().unlock();
}
private static void beginWriteLock()
{
rwLock.writeLock().lock();
}
private static void endWriteLock()
{
rwLock.writeLock().unlock();
}
then you can do your task like the following.
public static void doSomething()
{
SQLiteDatabase sldb = null;
try
{
beginReadLock();
MyDatabase mydb = new MyDatabase();
sldb = mldb.getReadableDatabase();
......
}
catch (Exception e)
{
......
}
finally
{
if (sldb != null)
{
try
{
sldb.close();
}
catch (Exception e) {}
}
endReadLock();
}
}
Enclose read operations with beginReadLock() and endReadLock(). Likewise, enclose write operations with beginWriteLock() and endWriteLock().
Months ago, by the solution described above, I could solve my own database-lock issue where multiple threads were trying to read/write-open a database simultaneously.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…