線程池隊列飽和策略

來源:互聯網
上載者:User

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();

        }

   }

}

 

from:http://blog.csdn.net/yangdengfeng2003/archive/2009/04/01/4042274.aspx

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.