0

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!

Saifur Rahman Mohsin
  • 929
  • 1
  • 11
  • 37
  • 1
    Use ExecutorService like fixedThreadPool with 5 threads. Use executeOnExecutor method of AsyncTask to run AsynTask on the ExecutorService. – jimmy0251 Oct 14 '15 at 15:19
  • Async task is not suitable for this purpose as the OS can kill the app anytime. Secondly, why so much processing on client-side, work must be done on server. – We are Borg Oct 14 '15 at 15:20
  • The problem I'm facing requires processing on the client side, that is why. There are even larger tasks such as the data generation that the app consumes which is indeed being done on the server. The list (which the for loop runs on) is basically the piecemeal collection of this huge data set which the server breaks up and feeds to the app. – Saifur Rahman Mohsin Oct 14 '15 at 15:59

1 Answers1

2

You should use ExecutorService for this purpose.

ExecutorService executorService = Executors.newFixedThreadPool(5);

new MyAsyncTask().executeOnExecutor(executorService);

jimmy0251
  • 16,293
  • 10
  • 36
  • 39