ThreadPoolExecutor的PriorityBlockingQueue类型转化问题

最近在使用ThreadPoolExecutor的时候碰到点问题,因为项目原因在使用ThreadPoolExecutor准备把BlockingQueue替换为PriorityBlockingQueue,从而实现对优先级任务处理的线程池,贴下代码先

public abstract class Event<T> implements Callable<T>,Comparable<Event>
ExecutorService executorService=new ThreadPoolExecutor(1,1,1,TimeUnit.SECONDS,new PriorityBlockingQueue());

然后当我进行以下操作的时候

executorService.submit(new Event() {
            @Override
            public Object call() throws Exception {
                ...
                return null;
            }
        }); 
  

出现了如下错误

java.lang.ClassCastException: java.util.concurrent.FutureTask cannot be cast to java.lang.Comparable
    at java.util.concurrent.PriorityBlockingQueue.siftUpComparable(PriorityBlockingQueue.java:357)
    at java.util.concurrent.PriorityBlockingQueue.offer(PriorityBlockingQueue.java:489)
    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1361)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)

找到java.util.concurrent.PriorityBlockingQueue.siftUpComparable方法:

private static  void siftUpComparable(int k, T x, Object[] array) {
        Comparable super T> key = (Comparable super T>) x;
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = array[parent];
            if (key.compareTo((T) e) >= 0)
                break;
            array[k] = e;
            k = parent;
        }
        array[k] = key;
    }

是在Comparable key = (Comparable) x;上出现问题,根据java.util.concurrent.FutureTask cannot be cast to java.lang.Comparable知道x的类型是java.util.concurrent.FutureTask。现在看看FutureTask

public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V>

可见FutureTask的确没有实现Comparable接口,但是我提交的Event是实现了Comparable接口的,究竟是因为什么原因导致其成为了FutureTask呢,结果在ThreadPoolExecutor的submit(Callable task)找到原因,它是在AbstractExecutorService中实现的。

public  Future submit(Callable task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }

重点在newTaskFor方法

protected  RunnableFuture newTaskFor(Callable callable) {
        return new FutureTask(callable);
    }

所以我提交的Event被转化为了FutureTask了,而FutureTask没有实现Comparable,所以才会报错
现在解决的方法有:
- 用一个ComparableFutureTask继承FutureTask并实现Comparable接口,但也必须要override ThreadPoolExecutornewTaskFor方法

另外需要注意的是PriorityBlockingQueue的实现是一个最小堆.

你可能感兴趣的:(Java)