0

I'm trying to implement a "PriorityThreadPoolExecutor".

So I declare the Executor:

static ThreadPoolExecutor threadPool =  
                new ThreadPoolExecutor(2, 100, 100, TimeUnit.SECONDS, queue); 

And the key for the prioritization is the queue paramether. Basically I need a PriorityBlockingQueue so I use the constructor:

PriorityBlockingQueue(int initialCapacity, Comparator<? super E> comparator);
queue = new PriorityBlockingQueue<mRunnable>(10,
        new Comparator<mRunnable>() {

            @Override
            public int compare(mRunnable lhs, mRunnable rhs) {
                return rhs.getPriority()-lhs.getPriority();
            }
        });

Where the mRunnable is:

public interface mRunnable extends Runnable {
    public int getPriority();
}

But here the compiler complains:

Type mismatch: cannot convert from PriorityBlockingQueue<mRunnable> 
       to PriorityBlockingQueue <Runnable>

I do not understand why is this error happening when mRunnable extends Runnable.

I could patch it changing the comparator:

new Comparator<Runnable>() {

    @Override
    public int compare(Runnable lhs, Runnable rhs) {
        if (lhs instanceof mRunnable && rhs instanceof mRunnable){
        return ((mRunnable)rhs).getPriority()-((mRunnable)lhs).getPriority();
        }
        return 0;
    }
});

But this is a ugly sollution imho.

Can you explain why is the Type mismatch is happening? Thanks

Addev
  • 31,819
  • 51
  • 183
  • 302

1 Answers1

2

Type mismatch is happening because of different Generic types, you should change your reference type from PriorityBlockingQueue<Runnable> to PriorityBlockingQueue <mRunnable>. Or PriorityBlockingQueue<? extends Runnable> for example.

udalmik
  • 7,838
  • 26
  • 40
  • then is the constructor of the threadpoolexecutor who complains =( – Addev Aug 20 '12 at 14:06
  • Yeah .. I see now. It is known issue, you can also check these links for workarounds: http://stackoverflow.com/questions/3545623/how-to-implement-priorityblockingqueue-with-threadpoolexecutor-and-custom-tasks/5485769#5485769 http://stackoverflow.com/questions/7792767/priority-threadpoolexecutor-in-java-android – udalmik Aug 20 '12 at 16:44