Does yieldIfContendedSafely () have a personal transaction benefit?

I have a lengthy operation that I am doing in a background thread. Since it is important for the operation to complete successfully or not to complete at all, I complete the entire operation in the transaction.

User interface aspects should be read-only in the database during this time. To avoid blocking the user interface, I am experimenting with inserting calls into db.yieldIfContendedSafely() into the main loop of the background operation.

This does what I want the user interface to no longer block, but it’s not entirely clear to me if this threatens with a loss of data integrity.

The javadoc for yieldIfContendedSafely() says:

Temporarily complete the transaction so that other threads execute. The transaction is considered successful so far. Do not call setTransactionSuccessful before calling this. When this returns a new transaction will be created, but will not be marked as successful. This assumes that there are no nested transactions (beginTransaction has only been called once) and will throw an exception if this is not the case.

Does this mean that my long-term operation is actually transferred to the database in separate pieces, or does the general transaction support enough state to complete the whole lot at a time at the end, thereby preserving the integrity of the data?

+4
source share
1 answer

Does this mean that my long-term operation is actually transferred to the database in separate fragments

Yes. In yieldIfContendedSafely() Android calls setTransactionSuccessful() , endTransaction() and starts a new transaction - making your statements in the process. There is no mechanism for rollback of a "real" transaction after its completion.

This behavior only occurs if there is another thread in the database, otherwise yieldIfContendedSafely() does nothing.

I checked this with the following scenario. I started two threads: one inserted data into a table using a transaction, the other read data from the same table. The transaction did not setTransactionSuccessful() , so usually everything returns at the end, leaving the table empty. I added a call to yieldIfContendedSafely() , after which the table was not empty and had data from a transaction.

+8
source

Source: https://habr.com/ru/post/1400189/


All Articles