Synchronize opening and closing of the database
This commit is contained in:
parent
c64e47dcd6
commit
f7de8a0e44
@ -309,8 +309,7 @@ public class PodDBAdapter {
|
|||||||
private static PodDBHelper dbHelper;
|
private static PodDBHelper dbHelper;
|
||||||
|
|
||||||
private static volatile SQLiteDatabase db;
|
private static volatile SQLiteDatabase db;
|
||||||
private static final Lock dbLock = new ReentrantLock();
|
private static int counter = 0;
|
||||||
private static final AtomicInteger counter = new AtomicInteger(0);
|
|
||||||
|
|
||||||
public static void init(Context context) {
|
public static void init(Context context) {
|
||||||
PodDBAdapter.context = context.getApplicationContext();
|
PodDBAdapter.context = context.getApplicationContext();
|
||||||
@ -328,25 +327,18 @@ public class PodDBAdapter {
|
|||||||
private PodDBAdapter() {
|
private PodDBAdapter() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public PodDBAdapter open() {
|
public synchronized PodDBAdapter open() {
|
||||||
int adapters = counter.incrementAndGet();
|
counter++;
|
||||||
Log.v(TAG, "Opening DB #" + adapters);
|
Log.v(TAG, "Opening DB #" + counter);
|
||||||
|
|
||||||
if ((db == null) || (!db.isOpen()) || (db.isReadOnly())) {
|
if (db == null || !db.isOpen() || db.isReadOnly()) {
|
||||||
try {
|
db = openDb();
|
||||||
dbLock.lock();
|
|
||||||
if ((db == null) || (!db.isOpen()) || (db.isReadOnly())) {
|
|
||||||
db = openDb();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
dbLock.unlock();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
private SQLiteDatabase openDb() {
|
private SQLiteDatabase openDb() {
|
||||||
SQLiteDatabase newDb = null;
|
SQLiteDatabase newDb;
|
||||||
try {
|
try {
|
||||||
newDb = dbHelper.getWritableDatabase();
|
newDb = dbHelper.getWritableDatabase();
|
||||||
newDb.enableWriteAheadLogging();
|
newDb.enableWriteAheadLogging();
|
||||||
@ -357,19 +349,14 @@ public class PodDBAdapter {
|
|||||||
return newDb;
|
return newDb;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void close() {
|
public synchronized void close() {
|
||||||
int adapters = counter.decrementAndGet();
|
counter--;
|
||||||
Log.v(TAG, "Closing DB #" + adapters);
|
Log.v(TAG, "Closing DB #" + counter);
|
||||||
|
|
||||||
if (adapters == 0) {
|
if (counter == 0) {
|
||||||
Log.v(TAG, "Closing DB, really");
|
Log.v(TAG, "Closing DB, really");
|
||||||
try {
|
db.close();
|
||||||
dbLock.lock();
|
db = null;
|
||||||
db.close();
|
|
||||||
db = null;
|
|
||||||
} finally {
|
|
||||||
dbLock.unlock();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user