3

I'm trying to make some ASyncTask to run simultaneously with a priority.

I've creating a ThreadPoolExecutor with an PriorityBlockingQueue and the propper comparator works nice for standard Runnables. But when calling

    new Task().executeOnExecutor(threadPool, (Void[]) null);

The Comparator of the PriorityBlockingQueue receives a Runnable (private) internal of the ASyncTask (called mFuture in the source code), so in the comparator I can't identify the runnables or read a "priority" value.

How can I solve that? Thanks

Addev
  • 31,819
  • 51
  • 183
  • 302

1 Answers1

6

Borrow source code from android.os.AsyncTask and make your own com.company.AsyncTask implementation, where you can control everything you want in your own code.

android.os.AsyncTask come with two ready baked executor, THREAD_POOL_EXECUTOR and SERIAL_EXECUTOR:

private static final BlockingQueue<Runnable> sPoolWorkQueue =
        new LinkedBlockingQueue<Runnable>(10);

/**
 * An {@link Executor} that can be used to execute tasks in parallel.
 */
public static final Executor THREAD_POOL_EXECUTOR
        = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

/**
 * An {@link Executor} that executes tasks one at a time in serial
 * order. This serialization is global to a particular process.
 */
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

in your com.company.AsyncTask, create another PRIORITY_THREAD_POOL_EXECUTOR and wrap all your implementation within this class (where you have visiablity to all internal fields), and use your AysncTask like so:

com.company.AsyncTask asyncTask = new com.company.AsyncTask();
asyncTask.setPriority(1);
asyncTask.executeOnExecutor(com.company.AsyncTask.PRIORITY_THREAD_POOL_EXECUTOR, (Void[]) null);

Check out my answer here and see how I create my own AsyncTask to make executeOnExecutor() works before API Level 11.

Community
  • 1
  • 1
yorkw
  • 40,926
  • 10
  • 117
  • 130
  • Hello. I would love to follow this suggestion (because I already have a working `CustomAsyncTask`), but I'm lost at the `PRIORITY_THREAD_POOL_EXECUTOR` ThreadPoolExecutor declaration. Could you give some insights? Thanks. – dentex Jun 27 '14 at 08:15
  • @demtex, PRIORITY_THREAD_POOL_EXECUTOR does not exist in official AsyncTask API, you need write it by yourself in your own CustomAsyncTask. – yorkw Jun 28 '14 at 05:59
  • Thanks, I'm explaining it better here:http://stackoverflow.com/questions/24461534/asynctask-on-executor-and-priorityblockingqueue-implementation-issue – dentex Jun 28 '14 at 06:31