From 8f25f5830a4620218996dcabb73a4ca923b1750a Mon Sep 17 00:00:00 2001 From: ByteHamster Date: Thu, 5 Nov 2020 20:58:43 +0100 Subject: [PATCH] Use lazy singleton instead of Bill Pugh singleton --- .../antennapod/core/storage/PodDBAdapter.java | 40 +++++++++---------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/core/src/main/java/de/danoeh/antennapod/core/storage/PodDBAdapter.java b/core/src/main/java/de/danoeh/antennapod/core/storage/PodDBAdapter.java index 935b06cd6..ad7f40700 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/storage/PodDBAdapter.java +++ b/core/src/main/java/de/danoeh/antennapod/core/storage/PodDBAdapter.java @@ -316,46 +316,44 @@ public class PodDBAdapter { + JOIN_FEED_ITEM_AND_MEDIA; private static Context context; + private static PodDBAdapter instance; - private static volatile SQLiteDatabase db; + private final SQLiteDatabase db; + private final PodDBHelper dbHelper; public static void init(Context context) { PodDBAdapter.context = context.getApplicationContext(); } - // Bill Pugh Singleton Implementation - private static class SingletonHolder { - private static final PodDBHelper dbHelper = new PodDBHelper(PodDBAdapter.context, DATABASE_NAME, null); - private static final PodDBAdapter dbAdapter = new PodDBAdapter(); - } - public static PodDBAdapter getInstance() { - return SingletonHolder.dbAdapter; + if (instance == null) { + instance = new PodDBAdapter(); + } + return instance; } private PodDBAdapter() { + dbHelper = new PodDBHelper(PodDBAdapter.context, DATABASE_NAME, null); + db = openDb(); } - public synchronized PodDBAdapter open() { - if (db == null || !db.isOpen() || db.isReadOnly()) { - db = openDb(); - } - return this; - } - - @SuppressLint("NewApi") private SQLiteDatabase openDb() { SQLiteDatabase newDb; try { - newDb = SingletonHolder.dbHelper.getWritableDatabase(); + newDb = dbHelper.getWritableDatabase(); newDb.disableWriteAheadLogging(); } catch (SQLException ex) { Log.e(TAG, Log.getStackTraceString(ex)); - newDb = SingletonHolder.dbHelper.getReadableDatabase(); + newDb = dbHelper.getReadableDatabase(); } return newDb; } + public synchronized PodDBAdapter open() { + // do nothing + return this; + } + public synchronized void close() { // do nothing } @@ -371,8 +369,8 @@ public class PodDBAdapter { * robolectric/robolectric#1890.

*/ public static void tearDownTests() { - db = null; - SingletonHolder.dbHelper.close(); + getInstance().dbHelper.close(); + instance = null; } public static boolean deleteDatabase() { @@ -380,7 +378,7 @@ public class PodDBAdapter { adapter.open(); try { for (String tableName : ALL_TABLES) { - db.delete(tableName, "1", null); + adapter.db.delete(tableName, "1", null); } return true; } finally {