ThreadPoolExecutor的PriorityBlockingQueue支持问题

本文探讨了在使用ThreadPoolExecutor时遇到的问题,即PriorityBlockingQueue无法正确处理FutureTask对象,导致ClassCastException异常。作者深入分析了问题根源,并提供了一个自定义的XThreadPoolExecutor解决方案,通过创建可比较的FutureTask实现任务的优先级调度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在使用ThreadPoolExecutor时遇到一个问题:当ThreadPoolExecutor使用的BlockingQueue为PriorityBlockingQueue时,会出现异常,原因是java.util.concurrent.FutureTask cannot be cast to java.lang.Comparable。Google之,发现有很多同样的问题,但没有给出解决方案,只能查看源代码以期能找到并解决问题。

首先根据Exception找到问题原因:

Exception in thread "main" java.lang.ClassCastException: java.util.concurrent.FutureTask cannot be cast to java.lang.Comparable
	at java.util.concurrent.PriorityBlockingQueue.siftUpComparable(PriorityBlockingQueue.java:347)
	at java.util.concurrent.PriorityBlockingQueue.offer(PriorityBlockingQueue.java:475)
	at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1329)
	at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:132)
...

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

private static <T> 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> {
...

public
interface Runnable {
...

public interface Future<V> {
...

可见FutureTask的确没有实现Comparable接口。但是我所提交的Task

public static class Task implements Callable<Integer>, Comparable<Task> {
...

是实现了Comparable接口的。我的Task为什么变成了FutureTask?只好找到ThreadPoolExecutor的submit(Callable<T> task)方法一看究竟,它是在AbstractExecutorService中实现的。

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

可以看到通过newTaskFor方法,我所提交的Task变成了FutureTask:

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

OK,看来问题就是出在FutureTask这个类上了:

public class FutureTask<V> implements RunnableFuture<V> {
    private final Sync sync;

    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        sync = new Sync(callable);
    }
...
    private final class Sync extends AbstractQueuedSynchronizer {
        private final Callable<V> callable;

        Sync(Callable<V> callable) {
            this.callable = callable;
        }
...

看来他是将我提交的Task的Comparable接口直接忽略了。现在的问题就变成了让FutureTask支持Comparable接口,最简单的方法是用一个ComparableFutureTask继承FutureTask并实现Comparable接口,但也必须要Override ThreadPoolExecutor的newTaskFor方法,显得有些麻烦。为此又继续Google,却没有发现一些更好的方法。先实现了再说。

package canghailan.util.concurrent;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author canghailan
 * @datetime 2011-12-10 13:57:19
 */
public class XThreadPoolExecutor extends ThreadPoolExecutor {

    public XThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
            long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    public XThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
            long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue,
            RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
    }

    public XThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
            long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue,
            ThreadFactory threadFactory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
    }

    public XThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
            long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue,
            ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    @Override
    protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        return new ComparableFutureTask<>(runnable, value);
    }

    @Override
    protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
        return new ComparableFutureTask<>(callable);
    }

    protected class ComparableFutureTask<V>
            extends FutureTask<V> implements Comparable<ComparableFutureTask<V>> {
        private Object object;

        public ComparableFutureTask(Callable<V> callable) {
            super(callable);
            object = callable;
        }

        public ComparableFutureTask(Runnable runnable, V result) {
            super(runnable, result);
            object = runnable;
        }

        @Override
        @SuppressWarnings("unchecked")
        public int compareTo(ComparableFutureTask<V> o) {
            if (this == o) {
                return 0;
            }
            if (o == null) {
                return -1; // high priority
            }
            if (object != null && o.object != null) {
                if (object.getClass().equals(o.object.getClass())) {
                    if (object instanceof Comparable) {
                        return ((Comparable) object).compareTo(o.object);
                    }
                }
            }
            return 0;
        }
    }
}

测试一下:

package canghailan;

import canghailan.util.concurrent.XThreadPoolExecutor;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Phaser;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author canghailan
 * @datetime 2011-12-10 7:09:39
 */
public class TestXThreadPoolExecutor {

    public static void main(String args[]) throws Exception {
        Phaser phaser = new Phaser(1);
        ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>();
        ExecutorService service = new XThreadPoolExecutor(
                5, 5, 0L, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>());
        for (int i = 0; i < 10; ++i) {
            phaser.register();
            service.submit(new Task(i, queue, phaser));
        }
        phaser.arriveAndAwaitAdvance();
        System.out.println(queue);
        service.shutdown();
    }

    public static class Task implements Callable<Integer>, Comparable<Task> {
        private Integer id;
        private ConcurrentLinkedQueue<Integer> queue;
        private Phaser phaser;

        public Task(Integer id, ConcurrentLinkedQueue<Integer> queue, Phaser phaser) {
            this.id = id;
            this.queue = queue;
            this.phaser = phaser;
        }

        @Override
        public Integer call() throws Exception {
            queue.offer(id);
            phaser.arrive();
            return id;
        }

        @Override
        public int compareTo(Task o) {
            return -id.compareTo(o.id);
        }
    }
}

输出为[0, 1, 2, 3, 9, 8, 7, 6, 5, 4],[0, 1, 2, 3, 4, 7, 6, 5, 9, 8],[0, 1, 2, 3, 4, 7, 6, 5, 9, 8]...。

根据结果来看,的确起作用了。先到此为止,如果有更好的办法,请不吝赐教。

转载于:https://my.oschina.net/canghailan/blog/37006

在 `ThreadPoolExecutor` 中,队列(`BlockingQueue<Runnable>`)是线程池任务调度的核心组件之一,用于存放提交但尚未执行的任务。队列的配置直接影响线程池的行为、性能以及资源利用率。 ### 队列的作用 - **任务缓冲**:当核心线程数已满时,新提交的任务会被放入队列中等待执行。 - **控制并发行为**:通过队列容量可以控制线程池的最大排队长度,进而影响是否创建新的非核心线程或触发拒绝策略。 - **异步处理协调**:合理配置队列有助于平衡生产者与消费者之间的速率差异,提升系统稳定性[^3]。 ### 常见的队列类型 1. **`LinkedBlockingQueue`** - 基于链表结构的阻塞队列。 - 可指定容量,默认为无界队列(Integer.MAX_VALUE)。 - 适用于大多数通用场景,如异步日志记录、批量数据处理等。 ```java BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(1000); ``` 2. **`ArrayBlockingQueue`** - 基于数组的有界阻塞队列。 - 需要指定固定大小。 - 更适合对内存使用有严格限制的场景。 ```java BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(500); ``` 3. **`SynchronousQueue`** - 不存储元素的阻塞队列。 - 每个插入操作必须等待一个移除操作,反之亦然。 - 适用于要求极高响应速度的场景,例如短生命周期任务处理。 ```java BlockingQueue<Runnable> queue = new SynchronousQueue<>(); ``` 4. **`PriorityBlockingQueue`** - 支持优先级排序的无界阻塞队列。 - 适用于需要根据任务优先级调度执行的场景。 ```java BlockingQueue<Runnable> queue = new PriorityBlockingQueue<>(); ``` 5. **`DelayQueue`** - 元素只有在其延迟时间到期后才能被取出。 - 适用于定时任务调度场景。 ```java BlockingQueue<Runnable> queue = new DelayQueue<>(); ``` ### 队列配置建议 - **有界 vs 无界**: - 使用有界队列(如 `ArrayBlockingQueue` 或带容量的 `LinkedBlockingQueue`)可以防止资源耗尽问题,避免任务无限堆积。 - 无界队列(如默认的 `LinkedBlockingQueue`)可能导致内存溢出,尤其在任务提交速度远大于消费速度时。 - **容量设置**: - 队列容量应结合业务负载进行评估。过小可能导致频繁触发拒绝策略;过大则可能掩盖系统瓶颈。 - 示例配置: ```java new ThreadPoolExecutor( 5, // corePoolSize 10, // maximumPoolSize 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000), // 队列容量设为1000 new ThreadPoolExecutor.CallerRunsPolicy() // 自定义拒绝策略 ); ``` - **与线程池参数配合使用**: - 当队列满时,若当前线程数小于最大线程数,则会创建新线程。 - 若线程数已达上限且队列已满,则触发拒绝策略(如抛出异常、调用者运行等)[^4]。 ### 队列使用的注意事项 - **线程安全**:所有 `BlockingQueue` 实现都是线程安全的,适合多线程环境下使用。 - **性能考量**:不同队列实现的性能表现有所差异,`LinkedBlockingQueue` 通常比 `ArrayBlockingQueue` 在高并发下表现更好。 - **拒绝策略匹配**:队列容量和拒绝策略应协同设计,确保在极端情况下系统仍能优雅降级[^5]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值