Click here to Skip to main content
14,867,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Recently I started using room database in my android app. I am getting some problems when trying to access database from multiple threads. I am using same instance of database in all threads.

 1. As far I know, if all threads have same instance of database then
    database access is serialized. I read in a blog that in serialized
    mode only one thread can read and write in database. However
    according to sqlite docs, read enables shared lock hence multiple
    thread can read simultaneously. So when using single instance of db,
    default locking criteria of sqlite which allows multiple read and
    one write operation is followed or not?
 2. According to sqlite docs, while writing to database first reserved lock is enabled and if any other write operation tries to get
    Reserved lock then write attempt fails and db returns SQLITE_BUSY.
    But if I am trying to run two write operation consequently from
    different threads I am never getting this error. Does it mean that
    write operation are queued and It's guaranteed that we will never
    get SQLITE_BUSY error, hence write operation will never fail?
 3.  I am doing a long insert operation(@Insert) in one thread(Thread1) and reading database in another thread(Thread2). If
    I start Thread2  just after Thread1, Read operation does not return the new
    inserted data in Thread1, so reading is happening before insertion.
    Is it happening because initially write enables Reserved lock and
    during this time new shared lock can be acquired @sqlite
    docs.

 4. continuum of 3: However if i do deletion in thread and read in thread2, then read is always happening after deletion, opposite to 3.
 5. Delete, Update, Insert all are write operation and follows same pattern of locking database?.

 6. this is unrelated to multi threading,  according to android developer guide, @query is **not** automatically wrapped in a transaction. A single Query(for reading) `@Query("SELECT * FROM forecast")` might happen in multiple transaction? 

Sorry for a long question.


What I have tried:

I tried running a weather app and accessed database from multiple threads.
Posted
Updated 19-Jul-18 22:56pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900