Reputation: 4124
Since I don't know how much time a db operations will take, it will be ok to call them in threads?
At the moment I have a ThreadPool class which contains an ExecutorService object which run the jobs added. Every db-related methods is added as a job so the ThreadPool will run it when a new thread will be available.
Which is the best way to make db operations?
Thank you.
Upvotes: 2
Views: 643
Reputation: 33505
Since I don't know how much time a db operations will take, it will be ok to call them in threads?
Short asnwer: Yes. You should perform db operations in Threads. You should keep your application's logic separated from application's appearance.
Which is the best way to make db operations?
Generally using Threads is i think the best practise you can choose. And kind of used tool(PoolExecutor, FutureTask, AsyncTask, native Thread) depends what you are expecting and supposed time of operation(always if operations lasts more than 1-2 seconds, threads should be used).
AsyncTask is appropriate to use if you want to inform potential USER
about about some progress in running task and it's worth to mention that is designated for tasks which will last ideally a few seconds.
For tasks that run for longer periods of time is appropriate to use mentioned API
tools from java.util.concurrent package like ThreadPool, ThreadPoolExecutor, FutureTask etc.
I'm using AsyncTask or native Thread for db operations. Usually they last max. a few seconds. Always you can improve your performance related to insertion, deletion and updating with TRANSACTIONS
. They can rapidly increase your for example insertion speed 1 and also provide safer way to deal with your database. Always it's very good, efficient and useful practise.
1 I made a few tests when i tested performance related to basic database operations and results were very interesting. I performed insertion of 100 000 records and difference was big. Whereas insertion with transaction took approx. 57,497 seconds, insertion without transaction took much more than 6 minutes. It's insane. Same with deletion and updating.
Upvotes: 4
Reputation: 28063
Perform async DB operations is totally fine.
I'm not sure which is the best way but AFAIK the standard one is to do it through Loaders (CursorLoader for accessing a ContentProvider or SQLiteCursorLoader for accessing SQLite databases).
You are free to use your own mechanism but be careful to prevent any potential memory leak.
Upvotes: 1