I need to call multiple api's each executing in separate thread and insert the respective data from response to sqlite database without causing locks. Can anyone help me in this regard with a working example that I can refer to.
1 Answers
I need to call multiple api's each executing in separate thread and insert the respective data from response to sqlite database without causing locks.
You don't need to do anything special. Multiple threads can make use of the same SQLiteDatabase
object without you doing locking at the application level. Sqlite does it's own locking under the covers. You should never get deadlocks but one thread will have to wait for the other thread to finish making its insert.
See these questions/answers:
Sqlite under Android is single threaded. Even if multiple threads were using the same database connection, my understanding is that they would be blocked from running concurrently. There is no way to get around this limitation. If you open two connections to the same database, this would corrupt the database because database updates would not be coordinated.
-
What about multiprocessing instead of threading where multiple processes are spawned at a time, can I use SQLIte for that purpose by using a single connection across the processes? – Volatil3 Aug 17 '22 at 05:07
-
I found this via Google @Volatil3: https://www.sqlite.org/faq.html#:~:text=Multiple%20processes%20can%20have%20the,control%20access%20to%20the%20database. – Gray Aug 22 '22 at 22:30
-
so how do I make sure inserts are not being done at same time while I am spawning multiple processes? – Volatil3 Aug 23 '22 at 04:03
-
Read that page. Sqlite uses file locking so only one process can update at a time. If anyone is updating then no one can be reading. – Gray Aug 24 '22 at 19:42