I have a for loop that creates several AsyncTasks. A large array of data
exists and the for loop processes each data and calls the executor with that data. The AsyncTask does some intensive processing on that data and this code works perfectly fine for small datasets i.e. the data array being small enough that not too many threads are created.
for(Data datum: data)
{
new SomeAsyncDataTask(datum, this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
However, it so happens that the data is massive and so running this on production i.e. on an actual Android device crashes the app due too many threads with a RejectedExecutionException. Also, there is a UI form by which user can feed data and manually call the same SomeAsyncDataTask AsyncTask
class as well.
I’m looking for a solution by which I can control this execution by limiting 5 AsyncTasks to run at a time and any additional tasks must be queued up. Also, when the user sends in a task if the queue has any non-running queued task I would prefer to put this user task at the top so that when a running task completes this task gets the chance to run and the other tasks come only later. Googling shows me some results; like there was something called a PriorityBlockingQueue but looking at the code confused me. Is that a solution? If so how to employ it on this scenario (for the code above). Kindly suggest solution--thank you!
You should use ExecutorService for this purpose.
ExecutorService executorService = Executors.newFixedThreadPool(5);
new MyAsyncTask().executeOnExecutor(executorService);