Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot perform operation because there is no current transaction when inserting into database

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:

enter image description here

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?

like image 815
Oleksandr Karaberov Avatar asked Apr 18 '13 17:04

Oleksandr Karaberov


1 Answers

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.

like image 96
Gray Avatar answered Oct 25 '22 18:10

Gray