开发者

Database access from different threads in Android

开发者 https://www.devze.com 2023-04-10 11:21 出处:网络
I have a Service that downloads data开发者_开发问答 from the Internet in AsyncTasks. It parses the data and store it in a db. The Service runs continuously.

I have a Service that downloads data开发者_开发问答 from the Internet in AsyncTasks. It parses the data and store it in a db. The Service runs continuously.

There is a change that a Activity attempts to read from the db while the Service is writing to it.

I have a database helper with several methods for writing and reading. Could this cause problems? Potentially trying to open the db from two different threads?


there has been talked and written many books about concurrency problems in db .

But using stackoverflow like a wikipedia i have found some interesting thing:

Sqlite on android lets you access the database from multiple procs for reads, but if you're currently writing from one process, reads and writes from other procs will throw an exception because the first write has a lock on the db.

Then the database is well protected from others threads . The bad news is that you must manage those exceptions , and can be a dirty work if you have a big database (meaning with big many tables with much data exchange)


As long as you're only using one instance of a SQLiteDatabase, you should be fine. Just make sure to only do your db read/write transactions within your database helper, and no other classes. Any transactions made with the same database object will be synchronized for you automatically.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号