Commit 33bf533c authored by Bartek Fabiszewski's avatar Bartek Fabiszewski
Browse files

Simplify synchronized db access, avoid potential race condition

parent be2e3c3a
Loading
Loading
Loading
Loading
+19 −15
Original line number Diff line number Diff line
@@ -16,8 +16,6 @@ import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.util.Log;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Gateway class for database access
 *
@@ -25,14 +23,13 @@ import java.util.concurrent.atomic.AtomicInteger;

class DbAccess {

    private static final AtomicInteger openCount = new AtomicInteger();
    private static int openCount;
    private static DbAccess sInstance;

    private static SQLiteDatabase db;
    private static DbHelper mDbHelper;
    private static final String TAG = DbAccess.class.getSimpleName();


    /**
     * Private constructor
     */
@@ -54,12 +51,15 @@ class DbAccess {
     * Opens database
     * @param context Context
     */
    synchronized void open(Context context) {
        if(openCount.incrementAndGet() == 1) {
    void open(Context context) {
        synchronized (DbAccess.class) {
            if (openCount++ == 0) {
                if (Logger.DEBUG) { Log.d(TAG, "[open]"); }
                mDbHelper = DbHelper.getInstance(context.getApplicationContext());
                db = mDbHelper.getWritableDatabase();
            }
        }
    }

    /**
     * Write location to database.
@@ -323,8 +323,11 @@ class DbAccess {
    /**
     * Closes database
     */
    synchronized void close() {
        if(openCount.decrementAndGet() == 0) {
    void close() {
        synchronized (DbAccess.class) {
            if (--openCount == 0) {
                if (Logger.DEBUG) { Log.d(TAG, "[close]"); }

                if (db != null) {
                    db.close();
                }
@@ -333,5 +336,6 @@ class DbAccess {
                }
            }
        }
    }

}
+1 −1
Original line number Diff line number Diff line
@@ -63,7 +63,7 @@ class DbHelper extends SQLiteOpenHelper {
     * @param context Context
     * @return DbHelper instance
     */
    public static synchronized DbHelper getInstance(Context context) {
    static DbHelper getInstance(Context context) {

        if (sInstance == null) {
            sInstance = new DbHelper(context.getApplicationContext());