Reputation: 17264
I'm making an app where I've to perform lot of background operations.
Which is the best class/API to perform above operation. I've been using AsyncTask
but I read somewhere that it has default limitation of 10 background operations and also above functional limitations.
I would also appreciate if you could share peace of code of achieving above tasks.
Upvotes: 0
Views: 952
Reputation: 3876
You want to use ThreadPools
A ThreadPool is a group of managed Thread, waiting to execute in parallel a set of assigned tasks put on a queue.
Java supply a lot of ways to manage the pool, from simple fixed sized pool to pools that dynamically grow based on the workload to maximise efficiency.
A typical pattern is to use threadpools for all the tasks android does not want you to execute on the UI thread (eg: network operations). However, most of the times your thread will then need to post the result on the UI - and this is prevented from outside the UI thread. This is how your create a thread pool:
ExecutorService threadExecutor = Executors.newFixedThreadPool( 3 );
threadExecutor.execute(new Runnable(){
public void run(){
//put here your network code
//when you get the result, either use
//view.post(new Runnable...);
//or
//AsynchTask
}
});
Depending on your needs, you can have multiple thread pools for different purposes, but in general, speaking about Android, it is better to keep the overall number of active thread low.
Depending on your hardware, the recommendation is 2 threads per core, but this can vary depending on the proportion of IO-bound (eg network) and CPU-bound (eg graphics) activities.
For prioritising the entries in the queue I would recommend you to create your own ThreadPoolExecutor as in http://www.javamex.com/tutorials/threads/thread_pools_queues.shtml but pass a PriorityQueue instead:
BlockingQueue q = new PriorityQueue<Runnable>();
ThreadPoolExecutor ex = new ThreadPoolExecutor(4, 10, 20, TimeUnit.SECONDS, q);
See also: How to implement PriorityBlockingQueue with ThreadPoolExecutor and custom tasks
Upvotes: 2
Reputation: 1904
Yes, thread pools are a good solution. But why do it yourself? I manage an open source project on sourceforge.net that can help you get going. I also wrote this article as an introduction: Managing Threads in Android
Upvotes: 0