Reputation: 3362
I have a list containing URLs of Images that I want to download with Android's DownloadManager. It's a pretty basic design to define a AsyncTask subclass that removes an object from the list and then invokes the DownloadManager. My problem is how to handle the parallelism of the AsyncTasks when each of those will list.get(curentIndex)
. To make things clear I want each Task (which will be running on the Executor so running in parallel amongst the others not only the Main Thread) to run atomically the action that
will remove the objects from the lists
will and increment the index
Upvotes: 0
Views: 66
Reputation: 769
This is in general a synchronization problem. There are many ways to tackle this. I would suggest something along the lines:
// Your index. Defaulted at 0. Thread safe Integer wrapper object.
// All set/get operations are guaranteed atomical.
AtomicInteger mIndex = new AtomicInteger(0);
// Your list. This is thread-safe. All mutative operations
// are atomical, and properly locked. The list is copied on each write.
// This solution, though it does what it needs to do, is SLOW. Don't use for
// large lists.
CopyOnWriteArrayList<Object> mList = ... ;
// Your async task. Maybe more of them.
AsyncTask mTask = ...;
// Anything here that should be thread safe.
ensurePrerequisites(mTask);
// Execute on thread pool to make sure they're parallel.
// CAUTION: You will still get only (CPU_CORE_COUNT + 1) max parallel tasks.
mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
public void synchronized ensurePrerequisites(AsyncTask task) {
// I assume you want to pass the values into the task.
int idx = mIndex.getAndIncrement();
task.setIndex(idx);
task.setObject(mList.remove(idx));
}
Upvotes: 1