From 7db228a4ba9938605b86c19f4085890d64697d4c Mon Sep 17 00:00:00 2001 From: Debanjan Chatterjee Date: Tue, 6 Feb 2024 00:08:03 +0530 Subject: [PATCH] fix: race condition fix using semaphore --- .../android/sdk/core/DBPersistentManager.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/com/rudderstack/android/sdk/core/DBPersistentManager.java b/core/src/main/java/com/rudderstack/android/sdk/core/DBPersistentManager.java index 79015277e..f5be6cc8b 100644 --- a/core/src/main/java/com/rudderstack/android/sdk/core/DBPersistentManager.java +++ b/core/src/main/java/com/rudderstack/android/sdk/core/DBPersistentManager.java @@ -6,7 +6,6 @@ import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabaseCorruptException; -import android.icu.text.Collator; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; @@ -33,6 +32,7 @@ import java.util.Queue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.Semaphore; /* * Helper class for SQLite operations @@ -316,6 +316,7 @@ void getEventsFromDB(Map messageIdStatusMap,//(id (row_id), st } Cursor cursor; synchronized (DB_LOCK) { + semaphore.acquire(); cursor = persistence.rawQuery(selectSQL, null); } if (!cursor.moveToFirst()) { @@ -341,6 +342,8 @@ void getEventsFromDB(Map messageIdStatusMap,//(id (row_id), st } catch (SQLiteDatabaseCorruptException ex) { RudderLogger.logError(ex); ReportManager.reportError(ex); + } catch (InterruptedException e) { + throw new RuntimeException(e); } } @@ -505,7 +508,14 @@ private boolean checkIfColumnExists(String newColumn) { return false; } + Semaphore semaphore = new Semaphore(1); + void checkForMigrations() { + try { + semaphore.acquire(); + } catch (InterruptedException e) { + //no-op + } Runnable runnable = () -> { try { boolean isNewColumnAdded = false; @@ -525,6 +535,8 @@ void checkForMigrations() { } catch (SQLiteDatabaseCorruptException | ConcurrentModificationException | NullPointerException ex) { RudderLogger.logError(DBPERSISTENT_MANAGER_CHECK_FOR_MIGRATIONS_TAG + ex.getLocalizedMessage()); + } finally { + semaphore.release(); } }; // Need to perform db operations on a separate thread to support strict mode.