如何将CompletableFuture.supplyAsync与PriorityBlockingQueue一起使用?

时间:2016-01-19 00:50:34

标签: java executorservice threadpoolexecutor java-threads completable-future

我试图通过CompletableFuture.supplyAsync将优先级队列添加到使用ThreadPoolExecutor和LinkedBlockingQueue的现有应用程序。问题在于,我无法设计分配任务优先级,然后我可以在PriorityBlockingQueue的比较器中访问。这是因为我的任务被CompletableFuture包装到一个名为AsyncSupply的私有内部类的实例中,该实例隐藏了私有字段中的原始任务。然后使用这些AsteSupply对象作为Runnables调用Comparator,如下所示:

public class PriorityComparator<T extends Runnable> implements Comparator<T> {

    @Override
    public int compare(T o1, T o2) {

        // T is an AsyncSupply object.
        // BUT I WANT SOMETHING I CAN ASSIGN PRIORITIES TOO!
        return 0;
    }
}

我研究了扩展CompletableFuture的可能性,因此我可以将它包装在一个不同的对象中,但很多CompletableFuture被封装且无法使用。因此,扩展它似乎不是一种选择。也没有用适配器封装它,因为它实现了一个非常宽的接口。

除了复制整个CompletableFuture并修改它之外,我不确定如何解决这个问题。有什么想法吗?

1 个答案:

答案 0 :(得分:5)

似乎API中的限制CompletableFuture没有提供使用PriorityBlockingQueue的简单方法。幸运的是,我们可以毫不费力地破解它。在Oracle的1.8 JVM中,它们碰巧命名所有内部类的字段fn,因此可以毫不费力地提取我们的优先级感知Runnable

public class CFRunnableComparator implements Comparator<Runnable> {

    @Override
    @SuppressWarnings("unchecked")
    public int compare(Runnable r1, Runnable r2) {
        // T might be AsyncSupply, UniApply, etc., but we want to
        // compare our original Runnables.
        return ((Comparable) unwrap(r1)).compareTo(unwrap(r2));
    }

    private Object unwrap(Runnable r) {
        try {
            Field field = r.getClass().getDeclaredField("fn");
            field.setAccessible(true);
            // NB: For performance-intensive contexts, you may want to
            // cache these in a ConcurrentHashMap<Class<?>, Field>.
            return field.get(r);
        } catch (IllegalAccessException | NoSuchFieldException e) {
            throw new IllegalArgumentException("Couldn't unwrap " + r, e);
        }
    }
}

这假设您的Supplier班级为Comparable,类似于:

public interface WithPriority extends Comparable<WithPriority> {
    int priority();
    @Override
    default int compareTo(WithPriority o) {
        // Reverse comparison so higher priority comes first.
        return Integer.compare(o.priority(), priority());
    }
}

public class PrioritySupplier<T> implements Supplier<T>, WithPriority {
    private final int priority;
    private final Supplier<T> supplier;
    public PrioritySupplier(int priority, Supplier<T> supplier) {
        this.priority = priority;
        this.supplier = supplier;
    }
    @Override
    public T get() {
        return supplier.get();
    }
    @Override
    public int priority() {
        return priority;
    }
}

使用如下:

PriorityBlockingQueue<Runnable> q = new PriorityBlockingQueue<>(11 /*default*/,
        new CFRunnableComparator());
ThreadPoolExecutor pool = new ThreadPoolExecutor(..., q);
CompletableFuture.supplyAsync(new PrioritySupplier<>(n, () -> {
    ...
}), pool);

如果您创建类似PriorityFunctionPriorityBiConsumer的类,则可以使用相同的技术调用具有适当优先级的thenApplyAsyncwhenCompleteAsync等方法。