线程池队列饱和策略

1、当一个有限队列充满后,线程池的饱和策略开始起作用。

2、ThreadPoolExecutor的饱和策略通过调用setRejectedExecutionHandler来修改。不同的饱和策略如下:

1)AbortPolicy:中止,executor抛出未检查RejectedExecutionException,调用者捕获这个异常,然后自己编写能满足自己需求的处理代码。

2)DiscardRunsPolicy:遗弃最旧的,选择丢弃的任务,是本应接下来就执行的任务。

3)DiscardPolicy:遗弃会默认放弃最新提交的任务(这个任务不能进入队列等待执行时)

4)CallerRunsPolicy:调用者运行,既不会丢弃哪个任务,也不会抛出任何异常,把一些任务推回到调用者那里,以此减缓新任务流。它不会在池线程中执行最新提交的任务,但它会在一个调用了execute的线程中执行。

3、创建一个可变长的线程池,使用受限队列和调用者运行饱和策略。

ThreadPoolExecutor executor=new ThreadPoolExecutor(N_THREADS,N_THREADS,0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(CAPACITY));

executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

4、当线程队列充满后,并没有预置的饱和策略来阻塞execute。但是,使用Semaphore信号量可以实现这个效果。Semaphore会限制任务注入率。

@ThreadSafe

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{ 

        semaphore.acquire();

        try{

            exec.execute(new Runnable(){

               public void run(){

                  try{

                          command.run();

                  }

                  finally{

                      semaphore.release();

                  }

               }

            });

        }catch (RejectedExecutionException e){

             semaphore.release();

        }

   }

}

原文地址:https://www.cnblogs.com/jiligalaer/p/3991177.html