如果它已经饱和,如何使ThreadPoolExecutor submit()方法块?

时间:2010-01-04 17:59:37

标签: java concurrency executor

我想创建一个ThreadPoolExecutor,以便当它达到最大大小且队列已满时,submit()方法阻止尝试添加新任务时。我是否需要为此实现自定义RejectedExecutionHandler,或者是否存在使用标准Java库执行此操作的方法?

18 个答案:

答案 0 :(得分:44)

我刚刚找到的一种可能的解决方案:

public class BoundedExecutor {
    private final Executor exec;
    private final Semaphore semaphore;

    public BoundedExecutor(Executor exec, int bound) {
        this.exec = exec;
        this.semaphore = new Semaphore(bound);
    }

    public void submitTask(final Runnable command)
            throws InterruptedException, RejectedExecutionException {
        semaphore.acquire();
        try {
            exec.execute(new Runnable() {
                public void run() {
                    try {
                        command.run();
                    } finally {
                        semaphore.release();
                    }
                }
            });
        } catch (RejectedExecutionException e) {
            semaphore.release();
            throw e;
        }
    }
}

还有其他解决方案吗?我更喜欢基于RejectedExecutionHandler的东西,因为它似乎是处理这种情况的标准方法。

答案 1 :(得分:28)

您可以使用ThreadPoolExecutor和blockingQueue:

public class ImageManager {
    BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(blockQueueSize);
    RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
    private ExecutorService executorService =  new ThreadPoolExecutor(numOfThread, numOfThread, 
        0L, TimeUnit.MILLISECONDS, blockingQueue, rejectedExecutionHandler);

    private int downloadThumbnail(String fileListPath){
        executorService.submit(new yourRunnable());
    }
}

答案 2 :(得分:12)

您应该使用CallerRunsPolicy,它在调用线程中执行被拒绝的任务。这样,在完成任务之前,它不能向执行程序提交任何新任务,此时将有一些空闲池线程或进程将重复。

http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ThreadPoolExecutor.CallerRunsPolicy.html

来自文档:

  

拒绝的任务

     

方法execute(java.lang.Runnable)中提交的新任务将是   执行人去过时被拒绝了   关闭,也是当Executor   使用有限边界来获得最大值   线程和工作队列容量,以及   已经饱和了。在任何一种情况下,   execute方法调用   RejectedExecutionHandler.rejectedExecution(一个java.lang.Runnable,   java.util.concurrent.ThreadPoolExecutor中)   它的方法   RejectedExecutionHandler。四   预定义处理程序策略   提供:

     
      
  1. 在默认的ThreadPoolExecutor.AbortPolicy中   处理程序抛出运行时   RejectedExecutionException on   排斥反应。
  2.   
  3. 在ThreadPoolExecutor.CallerRunsPolicy中,   调用的线程执行自己   运行任务。这提供了一个简单的   反馈控制机制将   减慢新任务的速度   提交。
  4.   
  5. 在ThreadPoolExecutor.DiscardPolicy中,a   无法执行的任务很简单   丢弃。
  6.   
  7. 在ThreadPoolExecutor.DiscardOldestPolicy中,   如果执行人没有关闭,那么   工作队列头部的任务是   丢弃,然后重试执行   (这可能会再次失败,导致这种情况发生   重复。)
  8.   

此外,在调用ThreadPoolExecutor构造函数时,请确保使用有界队列,例如ArrayBlockingQueue。否则,什么都不会被拒绝。

编辑:响应您的注释,将ArrayBlockingQueue的大小设置为等于线程池的最大大小,并使用AbortPolicy。

编辑2:好的,我知道你得到了什么。这样做:覆盖beforeExecute()方法以检查getActiveCount()是否超过getMaximumPoolSize(),如果确实如此,请再次睡觉并重试?

答案 3 :(得分:12)

执行此操作,请查看四个备选Creating a NotifyingBlockingThreadPoolExecutor

答案 4 :(得分:6)

Hibernate有一个BlockPolicy,它很简单,可以做你想做的事情:

请参阅:Executors.java

/**
 * A handler for rejected tasks that will have the caller block until
 * space is available.
 */
public static class BlockPolicy implements RejectedExecutionHandler {

    /**
     * Creates a <tt>BlockPolicy</tt>.
     */
    public BlockPolicy() { }

    /**
     * Puts the Runnable to the blocking queue, effectively blocking
     * the delegating thread until space is available.
     * @param r the runnable task requested to be executed
     * @param e the executor attempting to execute this task
     */
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        try {
            e.getQueue().put( r );
        }
        catch (InterruptedException e1) {
            log.error( "Work discarded, thread was interrupted while waiting for space to schedule: {}", r );
        }
    }
}

答案 5 :(得分:6)

上面引用的 Java Concurrency in Practice 中的BoundedExecutor答案只有在为Executor使用无界队列时才能正常工作,或者信号量绑定不大于队列大小。信号量是提交线程和池中的线程之间共享的状态,使得即使队列大小<1,也可以使执行器饱和。 bound&lt; =(队列大小+池大小)。

使用CallerRunsPolicy仅在您的任务不能永久运行时才有效,在这种情况下,您的提交线程将永久保留在rejectedExecution,如果您的任务需要很长时间才能运行,因为提交线程无法提交任何新任务或在其自身运行任务时执行任何其他操作。

如果这是不可接受的,那么我建议在提交任务之前检查执行者的有界队列的大小。如果队列已满,请等待一小段时间再尝试再次提交。吞吐量会受到影响,但我认为这是一个比许多其他提议的解决方案更简单的解决方案,并且保证不会有任何任务被拒绝。

答案 6 :(得分:5)

我知道,这是一个黑客,但在我看来,这里提供的最干净的黑客; - )

因为ThreadPoolExecutor使用阻塞队列“offer”而不是“put”,所以让我们覆盖阻塞队列的“offer”行为:

class BlockingQueueHack<T> extends ArrayBlockingQueue<T> {

    BlockingQueueHack(int size) {
        super(size);
    }

    public boolean offer(T task) {
        try {
            this.put(task);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return true;
    }
}

ThreadPoolExecutor tp = new ThreadPoolExecutor(1, 2, 1, TimeUnit.MINUTES, new BlockingQueueHack(5));

我测试了它似乎工作。 实施一些超时策略留给读者练习。

答案 7 :(得分:2)

你可以使用像这样的自定义RejectedExecutionHandler

ThreadPoolExecutor tp= new ThreadPoolExecutor(core_size, // core size
                max_handlers, // max size 
                timeout_in_seconds, // idle timeout 
                TimeUnit.SECONDS, queue, new RejectedExecutionHandler() {
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        // This will block if the queue is full
                        try {
                            executor.getQueue().put(r);
                        } catch (InterruptedException e) {
                            System.err.println(e.getMessage());
                        }

                    }
                });

答案 8 :(得分:0)

我并不总是喜欢CallerRunsPolicy,特别是因为它允许被拒绝的任务跳过队列&#39;并在之前提交的任务之前执行。此外,在调用线程上执行任务可能需要比等待第一个插槽可用的时间长得多。

我使用自定义RejectedExecutionHandler解决了这个问题,它只是暂时阻塞调用线程,然后再次尝试提交任务:

public class BlockWhenQueueFull implements RejectedExecutionHandler {

    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

        // The pool is full. Wait, then try again.
        try {
            long waitMs = 250;
            Thread.sleep(waitMs);
        } catch (InterruptedException interruptedException) {}

        executor.execute(r);
    }
}

此类只能在线程池执行程序中用作RejectedExecutinHandler,例如:

executorPool = new ThreadPoolExecutor(1, 1, 10,
                                      TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
                                      new BlockWhenQueueFull());

我看到的唯一不足之处是调用线程可能会被锁定的时间略长于严格必要(最长250ms)。此外,由于这个执行程序实际上是递归调用的,因此很长时间等待线程可用(小时)可能导致堆栈溢出。

然而,我个人喜欢这种方法。它结构紧凑,易于理解,效果很好。

答案 9 :(得分:0)

这里的解决方案似乎非常有效。它被称为NotifyingBlockingThreadPoolExecutor

Demo program.

编辑:这个代码有issue,await()方法有问题。调用shutdown()+ awaitTermination()似乎工作正常。

答案 10 :(得分:0)

我最近需要在ScheduledExecutorService上实现类似的功能。

我还必须确保我处理在方法上传递的延迟,并确保在调用者期望的时候提交任务以执行,或者只是失败因此抛出RejectedExecutionException

来自ScheduledThreadPoolExecutor执行或提交任务的其他方法在内部调用#schedule,这仍然会调用覆盖的方法。

import java.util.concurrent.*;

public class BlockingScheduler extends ScheduledThreadPoolExecutor {
    private final Semaphore maxQueueSize;

    public BlockingScheduler(int corePoolSize,
                             ThreadFactory threadFactory,
                             int maxQueueSize) {
        super(corePoolSize, threadFactory, new AbortPolicy());
        this.maxQueueSize = new Semaphore(maxQueueSize);
    }

    @Override
    public ScheduledFuture<?> schedule(Runnable command,
                                       long delay,
                                       TimeUnit unit) {
        final long newDelayInMs = beforeSchedule(command, unit.toMillis(delay));
        return super.schedule(command, newDelayInMs, TimeUnit.MILLISECONDS);
    }

    @Override
    public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                           long delay,
                                           TimeUnit unit) {
        final long newDelayInMs = beforeSchedule(callable, unit.toMillis(delay));
        return super.schedule(callable, newDelayInMs, TimeUnit.MILLISECONDS);
    }

    @Override
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit) {
        final long newDelayInMs = beforeSchedule(command, unit.toMillis(initialDelay));
        return super.scheduleAtFixedRate(command, newDelayInMs, unit.toMillis(period), TimeUnit.MILLISECONDS);
    }

    @Override
    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long period,
                                                     TimeUnit unit) {
        final long newDelayInMs = beforeSchedule(command, unit.toMillis(initialDelay));
        return super.scheduleWithFixedDelay(command, newDelayInMs, unit.toMillis(period), TimeUnit.MILLISECONDS);
    }

    @Override
    protected void afterExecute(Runnable runnable, Throwable t) {
        super.afterExecute(runnable, t);
        try {
            if (t == null && runnable instanceof Future<?>) {
                try {
                    ((Future<?>) runnable).get();
                } catch (CancellationException | ExecutionException e) {
                    t = e;
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt(); // ignore/reset
                }
            }
            if (t != null) {
                System.err.println(t);
            }
        } finally {
            releaseQueueUsage();
        }
    }

    private long beforeSchedule(Runnable runnable, long delay) {
        try {
            return getQueuePermitAndModifiedDelay(delay);
        } catch (InterruptedException e) {
            getRejectedExecutionHandler().rejectedExecution(runnable, this);
            return 0;
        }
    }

    private long beforeSchedule(Callable callable, long delay) {
        try {
            return getQueuePermitAndModifiedDelay(delay);
        } catch (InterruptedException e) {
            getRejectedExecutionHandler().rejectedExecution(new FutureTask(callable), this);
            return 0;
        }
    }

    private long getQueuePermitAndModifiedDelay(long delay) throws InterruptedException {
        final long beforeAcquireTimeStamp = System.currentTimeMillis();
        maxQueueSize.tryAcquire(delay, TimeUnit.MILLISECONDS);
        final long afterAcquireTimeStamp = System.currentTimeMillis();
        return afterAcquireTimeStamp - beforeAcquireTimeStamp;
    }

    private void releaseQueueUsage() {
        maxQueueSize.release();
    }
}

我在这里有代码,会感激任何反馈。 https://github.com/AmitabhAwasthi/BlockingScheduler

答案 11 :(得分:0)

我在弹性搜索客户端中找到了此拒绝政策。它阻塞阻塞队列上的调用者线程。代码如下 -

 static class ForceQueuePolicy implements XRejectedExecutionHandler 
 {
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) 
        {
            try 
            {
                executor.getQueue().put(r);
            } 
            catch (InterruptedException e) 
            {
                //should never happen since we never wait
                throw new EsRejectedExecutionException(e);
            }
        }

        @Override
        public long rejected() 
        {
            return 0;
        }
}

答案 12 :(得分:0)

我过去也有同样的需求:一种由共享线程池支持的每个客户端具有固定大小的阻塞队列。我最后编写了自己的ThreadPoolExecutor:

UserThreadPoolExecutor  (阻塞队列(每个客户端)+线程池(在所有客户端之间共享))

请参阅:https://github.com/d4rxh4wx/UserThreadPoolExecutor

每个UserThreadPoolExecutor都会从共享的ThreadPoolExecutor获得最大线程数

每个UserThreadPoolExecutor都可以:

  • 如果未达到配额,则将任务提交给共享线程池执行程序。如果达到其配额,则作业将排队(非消耗性阻塞等待CPU)。一旦其提交的任务之一完成,配额就会减少,允许另一个任务等待提交给ThreadPoolExecutor
  • 等待剩余的任务完成

答案 13 :(得分:0)

我相信通过使用java.util.concurrent.Semaphore并委派Executor.newFixedThreadPool的行为,可以通过非常优雅的方式解决此问题。 新的执行程序服务只有在有线程执行时才会执行新任务。阻塞由Semaphore管理,许可数等于线程数。任务完成后,返回许可证。

public class FixedThreadBlockingExecutorService extends AbstractExecutorService {

private final ExecutorService executor;
private final Semaphore blockExecution;

public FixedThreadBlockingExecutorService(int nTreads) {
    this.executor = Executors.newFixedThreadPool(nTreads);
    blockExecution = new Semaphore(nTreads);
}

@Override
public void shutdown() {
    executor.shutdown();
}

@Override
public List<Runnable> shutdownNow() {
    return executor.shutdownNow();
}

@Override
public boolean isShutdown() {
    return executor.isShutdown();
}

@Override
public boolean isTerminated() {
    return executor.isTerminated();
}

@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
    return executor.awaitTermination(timeout, unit);
}

@Override
public void execute(Runnable command) {
    blockExecution.acquireUninterruptibly();
    executor.execute(() -> {
        try {
            command.run();
        } finally {
            blockExecution.release();
        }
    });
}

答案 14 :(得分:0)

最近我发现这个问题有同样的问题。 OP没有明确说明,但我们不想使用在提交者线程上执行任务的RejectedExecutionHandler,因为如果此任务长时间运行,这将不足以利用工作线程之一。

阅读所有答案和评论,特别是使用信号量或使用afterExecute的有缺陷的解决方案我仔细查看了ThreadPoolExecutor的代码,看看是否有某种出路。我惊讶地发现有超过2000行(注释)代码,其中一些让我觉得dizzy。鉴于我实际上有一个相当简单的要求 - 一个生产者,几个消费者,让生产者阻止没有消费者可以工作 - 我决定推出自己的解决方案。它不是ExecutorService,而只是Executor。并且它不会使线程数量适应工作负载,但仅保留固定数量的线程,这也符合我的要求。这是代码。随意咆哮: - )

package x;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;

/**
 * distributes {@code Runnable}s to a fixed number of threads. To keep the
 * code lean, this is not an {@code ExecutorService}. In particular there is
 * only very simple support to shut this executor down.
 */
public class ParallelExecutor implements Executor {
  // other bounded queues work as well and are useful to buffer peak loads
  private final BlockingQueue<Runnable> workQueue =
      new SynchronousQueue<Runnable>();
  private final Thread[] threads;

  /*+**********************************************************************/
  /**
   * creates the requested number of threads and starts them to wait for
   * incoming work
   */
  public ParallelExecutor(int numThreads) {
    this.threads = new Thread[numThreads];
    for(int i=0; i<numThreads; i++) {
      // could reuse the same Runner all over, but keep it simple
      Thread t = new Thread(new Runner());
      this.threads[i] = t;
      t.start();
    }
  }
  /*+**********************************************************************/
  /**
   * returns immediately without waiting for the task to be finished, but may
   * block if all worker threads are busy.
   * 
   * @throws RejectedExecutionException if we got interrupted while waiting
   *         for a free worker
   */
  @Override
  public void execute(Runnable task)  {
    try {
      workQueue.put(task);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new RejectedExecutionException("interrupt while waiting for a free "
          + "worker.", e);
    }
  }
  /*+**********************************************************************/
  /**
   * Interrupts all workers and joins them. Tasks susceptible to an interrupt
   * will preempt their work. Blocks until the last thread surrendered.
   */
  public void interruptAndJoinAll() throws InterruptedException {
    for(Thread t : threads) {
      t.interrupt();
    }
    for(Thread t : threads) {
      t.join();
    }
  }
  /*+**********************************************************************/
  private final class Runner implements Runnable {
    @Override
    public void run() {
      while (!Thread.currentThread().isInterrupted()) {
        Runnable task;
        try {
          task = workQueue.take();
        } catch (InterruptedException e) {
          // canonical handling despite exiting right away
          Thread.currentThread().interrupt(); 
          return;
        }
        try {
          task.run();
        } catch (RuntimeException e) {
          // production code to use a logging framework
          e.printStackTrace();
        }
      }
    }
  }
}

答案 15 :(得分:0)

避免@FixPoint解决方案出现问题。可以使用ListeningExecutorService并在FutureCallback中释放信号量onSuccess和onFailure。

答案 16 :(得分:0)

你应该看看this link (notifying-blocking-thread-pool)总结了几个解决方案,最后给出一个优雅的解决方案。

答案 17 :(得分:0)

创建自己的阻塞队列以供Executor使用,具有您正在寻找的阻塞行为,同时始终返回可用的剩余容量(确保执行程序不会尝试创建比其核心池更多的线程,或触发拒绝处理程序)。

我相信这会让你获得正在寻找的阻止行为。拒绝处理程序永远不适合账单,因为这表明执行程序无法执行任务。我可以想象的是,你在处理程序中得到某种形式的“忙碌等待”。这不是你想要的,你想要一个阻止调用者的执行器队列......