Skip to content

Commit

Permalink
fix: race condition fix using semaphore
Browse files Browse the repository at this point in the history
  • Loading branch information
itsdebs committed Feb 5, 2024
1 parent ad9baa0 commit 7db228a
Showing 1 changed file with 13 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -316,6 +316,7 @@ void getEventsFromDB(Map<Integer, Integer> messageIdStatusMap,//(id (row_id), st
}
Cursor cursor;
synchronized (DB_LOCK) {
semaphore.acquire();
cursor = persistence.rawQuery(selectSQL, null);
}
if (!cursor.moveToFirst()) {
Expand All @@ -341,6 +342,8 @@ void getEventsFromDB(Map<Integer, Integer> messageIdStatusMap,//(id (row_id), st
} catch (SQLiteDatabaseCorruptException ex) {
RudderLogger.logError(ex);
ReportManager.reportError(ex);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}

Expand Down Expand Up @@ -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;
Expand All @@ -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.
Expand Down

0 comments on commit 7db228a

Please sign in to comment.