In my Android application I have to insert data into several SQLite tables from different threads (one thread for insertion into one table and there are 5 tables). There are a lot of data so I use beginTransaction()
-> setTransactionSuccessful()
-> endTransaction();
in every thread and all the threads start simultaneously, but in second or sometimes third thread I always got this exception:
I use single SQLite connection (singleton) as was mentioned here but nevertheless this problem remains.So I hope for some help.Thanks in advance!
P.S And if I have race conditions what other way should I use for multithreaded insertion?
I think your problem is a race condition. Since you have multiple threads that are starting and ending the transaction, you might get something like the following operations:
beginTransaction()
// this may be a noop because a transaction is already open
beginTransaction()
setTransactionSuccessful()
setTransactionSuccessful()
endTransaction()
// this may throw because the previous end closes the transaction
endTransaction()
I don't think that Sqlite supports multiple transactions open on a single connection and as you point out, multiple connections is not possible.
If the goal of the transactions is to speed up the data, then you are going to have to change your architecture and not write from multiple threads. You can use some sort of utility class to do the actual database updates that is synchronized
so all threads call in and it decides when to open or close a transaction. Another idea would be to have a single thread do your database operations and all other threads write into a BlockingQueue
that is shared with the writing thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With