problems with callBatchTasks(...) and multiple threads

130 views
Skip to first unread message

Gray Watson

unread,
Feb 16, 2015, 5:41:58 PM2/16/15
to ORMLite Android
Hey folks:

I've been looking at the following two android issues:

https://github.com/j256/ormlite-android/issues/16
https://github.com/j256/ormlite-android/issues/34

After looking at the code and thinking about it a bit, I've realized that you cannot have multiple-threads using dao.callBatchTasks(...) at the same time. I've just added the following to the javadocs for dao.callBatchTasks() and dao.setAutoCommit(...).

NOTE: Depending on your underlying database implementation and whether or not you
are working with a single database connection, you may need to synchronize around
calls to this method otherwise the database transactions that are used may clash
when called simultaneously from multiple threads. Android users need to synchronize.
You may also need to synchronize other calls to transactions and dao.setAutoCommit(...).

I'm not sure if ORMLite should be forcing synchronization here but certainly while the warning is in place, you need to protect this section of code. The problem is that under the covers we are dealing with a single database connection and yet we are doing approximately:

db.startTransaction();
callable.call();
db.endTransaction();

If multiple threads are calling this then transactions race conditions are in effect.

Comments?
gray

Gray Watson

unread,
Feb 17, 2015, 11:37:44 AM2/17/15
to ORMLite Android
Ok. In 4.49 I've added code to make an attempt at detecting if the connection-source is backed with a single-connection (such as Android). When it is a single connection, it will synchronize on an internal object to stop concurrent usage of callBatchTasks(...).

This was necessary because of the underlying single-connection and that multiple threads would be starting and stopping transactions when other threads were updating the database using the same connection. Under the covers Sqlite locks and protects against any problems but ORMLite needs also to lock otherwise the transaction race-conditions could cause data issues.

Comments?
gray

Reply all
Reply to author
Forward
0 new messages