最近在使用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
出现了如下错误
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 super T> key = (Comparable super T>) 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
找到原因,它是在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 ThreadPoolExecutor
的newTaskFor
方法
另外需要注意的是PriorityBlockingQueue
的实现是一个最小堆.