Created
March 24, 2014 03:23
-
-
Save xalexchen/9733607 to your computer and use it in GitHub Desktop.
DatabaseManager(thread safe) from https://github.com/dmytrodanylyk/dmytrodanylyk/blob/gh-pages/articles/Concurrent%20Database%20Access.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DatabaseManager { | |
private AtomicInteger mOpenCounter = new AtomicInteger(); | |
private static DatabaseManager instance; | |
private static SQLiteOpenHelper mDatabaseHelper; | |
private SQLiteDatabase mDatabase; | |
public static synchronized void initializeInstance(SQLiteOpenHelper helper) { | |
if (instance == null) { | |
instance = new DatabaseManager(); | |
mDatabaseHelper = helper; | |
} | |
} | |
public static synchronized DatabaseManager getInstance() { | |
if (instance == null) { | |
throw new IllegalStateException(DatabaseManager.class.getSimpleName() + | |
" is not initialized, call initializeInstance(..) method first."); | |
} | |
return instance; | |
} | |
public synchronized SQLiteDatabase openDatabase() { | |
if(mOpenCounter.incrementAndGet() == 1) { | |
// Opening new database | |
mDatabase = mDatabaseHelper.getWritableDatabase(); | |
} | |
return mDatabase; | |
} | |
public synchronized void closeDatabase() { | |
if(mOpenCounter.decrementAndGet() == 0) { | |
// Closing database | |
mDatabase.close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment