Is Sqlite Database instance thread safe

后端 未结 4 1028
小蘑菇
小蘑菇 2020-12-03 02:45

I have a database with some tables. I want to update the tables using multiple threads. I will use same instance of SQLiteDatabase in all threads.

Please suggest if

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 03:17

    The Android uses java locking mechanism to keep SQLite database access serialized. So, if multiple thread have one db instance, it always calls to the database in serialized manner and of course database is thread-safe.

    If we confirm that we are using database from single thread we had option to set database internal locking disable by calling setLockingEnable(false) but this method got deprecated from API level 16 and no longer in use. if you see the implementation of this method in SQLiteDatabase class, you will find nothing written there i.e. empty method.

    public void setLockingEnabled (boolean lockingEnabled)
    

    This method now does nothing. Do not use.

    One thing which we should take care of that is we should make one instance of your helper class(i.e. by making it singleton) and share same instance to multiple thread and do not call close() on database in between operation, otherwise you may get following exception:

    java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase

    So, do not call database.close() in between accessing the database, database will self perform close operation internally when all the operation would be finish.

提交回复
热议问题