Search code examples
androidandroid-room

Could Android use disk space to queue a SQLite transaction?


I would like to make a huge transaction with Androidx Room, something like the following:

@Transaction
fun addGeneratedRows() {
  for (i in 0 until 5_000_000) {
    addItem(generateRowWhichTakesUpALotOfMemory())
  }
}
@Insert fun addItem(itm: MyLargeRow) 

Now, I am worried this may lead to an Out of Memory error if Room will store the entire transaction in RAM before writing it to the database.

But I can imagine it might buffer the rows onto disk, allowing the garbage collector to purge the object in between the passes of for, since they are generated on the fly.

Well, will it? I cannot seem to find a source that it does, but also no source that it definitely does not.


Solution

  • Without having it thoroughly tested, I'm pretty this won't be a problem for the database. Room relies on the transaction mechanism of SQLite which in turn writes a journal of all changes to disk so it can (almost) instantly atomically either commit or roll back the entire transaction. How much and which parts of the journal is managed in memory I'm not sure about, but I'm pretty sure the raw data is already written to disk during the loop.

    With your code you could probably quite easily test this by adding another 0 to the number of entries and look at the free memory of the device when you run this.