1

タスク キューがいっぱいになったときにブロックする ThreadPoolExecutor を探しています。現在の Java 実装では、基になるキューがいっぱいになると新しいタスクが拒否されます。

public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    /*
     * Proceed in 3 steps:
     *
     * 1. If fewer than corePoolSize threads are running, try to
     * start a new thread with the given command as its first
     * task.  The call to addWorker atomically checks runState and
     * workerCount, and so prevents false alarms that would add
     * threads when it shouldn't, by returning false.
     *
     * 2. If a task can be successfully queued, then we still need
     * to double-check whether we should have added a thread
     * (because existing ones died since last checking) or that
     * the pool shut down since entry into this method. So we
     * recheck state and if necessary roll back the enqueuing if
     * stopped, or start a new thread if there are none.
     *
     * 3. If we cannot queue task, then we try to add a new
     * thread.  If it fails, we know we are shut down or saturated
     * and so reject the task.
     */
    int c = ctl.get();
    if (workerCountOf(c) < corePoolSize) {
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }
    if (isRunning(c) && workQueue.offer(command)) {
        int recheck = ctl.get();
        if (! isRunning(recheck) && remove(command))
            reject(command);
        else if (workerCountOf(recheck) == 0)
            addWorker(null, false);
    }
    else if (!addWorker(command, false))
        reject(command);
}

この行を変更します:

 if (isRunning(c) && workQueue.offer(command)) {

 if (isRunning(c) && workQueue.put(command)) {

トリックを行いますか?何か不足していますか?

解決策(次の人を助けるかもしれません):

public class BlockingThreadPoolExecutor extends ThreadPoolExecutor {

    private final Semaphore runLock;

    public BlockingThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
            long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, int maxTasks) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        runLock = new Semaphore(maxTasks);
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        runLock.acquireUninterruptibly();
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        runLock.release();
    }

}
4

1 に答える 1

4

ThreadPoolExecutorすべてのタスク送信が を通過するとは限らないため、状態と設定によって異なりますBlockingQueue。通常は、RejectedExecutionHandlerのを に変更ThreadPoolExecutorしてThreadPoolExecutor.CallerRunsPolicy送信を抑制します。送信時に本当にブロックしたい場合は、CompletionService を使用し、ブロックするときに「take」メソッドを呼び出す必要があります。サブクラスを作成し、 a を使用しSemaphoreて execute メソッドをブロックすることもできます。詳細については、JDK-6648211 : ThreadPoolExecutor をブロックする必要があるを参照してください。

于 2013-10-16T22:07:42.120 に答える