views:

110

answers:

1

I've searched a lot but could not find a solutuion to my problem.

I have my own class, BaseTask, that uses a ThreadPoolExecutor to handle tasks.
If I don't want prioritization (i.e. using a LinkedBlockingQueue) this works just fine, but when I try to use a PriorityBlockingQueue I get ClassCastException because the ThreadPoolExecutor wraps my Tasks into a FutureTask object.
This is obviously OK because the FutureTaskdoes not implement Comparable, but how would I go on to solve the priority problem?
I've read that you could override newTaskFor in ThreadPoolExecutor, but I can not seem to find this method at all...?

Any suggestions would be much appreciated!

Some code to help:

In my BaseTask class I have

private static final BlockingQueue<Runnable> sWorkQueue = new PriorityBlockingQueue<Runnable>();

private static final ThreadFactory sThreadFactory = new ThreadFactory() {
    private final AtomicInteger mCount = new AtomicInteger(1);

    public Thread newThread(Runnable r) {
        return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
    }
};

private static final BaseThreadPoolExecutor sExecutor = new BaseThreadPoolExecutor(
    1, Integer.MAX_VALUE, 10, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);

private final BaseFutureTask<Result> mFuture;

public BaseTask(int priority) {
    mFuture = new BaseFutureTask<Result>(mWorker, priority);
}

public final BaseTask<Params, Progress, Result> execute(Params... params) {

    /* Some unimportant code here */

    sExecutor.execute(mFuture);
}

In BaseFutureTask class

@Override
public int compareTo(BaseFutureTask another) {
    long diff = this.priority - another.priority;

    return Long.signum(diff);
}

In BaseThreadPoolExecutor class i override the 3 submit methods...
The constructor in this class gets called, but none of the submit methods

A: 

It looks like they left that out of apache harmony. There is a svn commit log about a year ago fixing the absence of newTaskFor. You can probably just override the submit functions in an extended ThreadPoolExecutor to create an extended FutureTask that is Comparable. They are not very long.

Qberticus
Well, I don't have to create an extended `ThreadPoolExecutor` right? I can just call `execute` with my extended and `Comparable` `FutureTask` as the `Runnable`?
greve
No, you have to extend it. It gets wrapped in a FutureTask in the various submit methods.
Qberticus
It doesn't seem like any of the `submit` methods gets called... Added some code to help understand
greve
Don't call `ThreadPoolExecutor#execute` anymore. Anything you want to have done by the thread pool will need to go in via a `submit` call. The `submit` methods should then call `execute` for you.
Qberticus
But the only thing the `submit` method does is just that, call the `execute` method... It creates a new `BaseFutureTask` and then executes it
greve