Java Executor 架構學習總結

來源:互聯網
上載者:User

Java Executor 架構學習總結

大多數並發都是通過任務執行的方式來實現的。一般有兩種方式執行任務:串列和並行。

 
  1. class SingleThreadWebServer { 
  2.   public static void main(String[] args) throws Exception { 
  3.     ServerSocket socket = new ServerSocket(80); 
  4.     while(true) { 
  5.       Socket conn = socket.accept(); 
  6.       handleRequest(conn); 
  7.     } 
  8.   } 
  9. class ThreadPerTaskWebServer { 
  10.   public static void main(String[] args) throws Exception { 
  11.     ServerSocket socket = new ServerSocket(80); 
  12.     while(true) { 
  13.       final Socket conn = socket.accept(); 
  14.       Runnable task = new Runnable() { 
  15.         public void run() { 
  16.           handleRequest(conn); 
  17.         } 
  18.       }; 
  19.       new Thread(task).start(); 
  20.     } 
  21.   } 

當然上面的這兩種方式都是有問題的。單線程的問題就是並發量會是瓶頸,多線程版本就是無限制的建立線程會導致資源不足問題。

Executor 架構

任務是一組邏輯工作單元,而線程是使任務非同步執行的機制。

JDK 提供了 Executor 介面:

 
  1. public interface Executor { 
  2.     void execute(Runnable command); 

雖然 Executor 介面比較簡單,但是卻是非同步任務執行架構的基礎,該架構能支援多種不同類型的任務執行策略。它提供了一種標準的方式把任務的提交過程與執行過程進行瞭解 耦。用 Runnable 來代表任務。Executor 的實現提供了對生命週期的支援以及統計資訊應用程式管理等機制。

Executor 是基於生產者消費者模式的,提交任務的操作相當於生產者,執行任務的線程相當於消費。

基於 Executor 的 WebServer 例子如下:

 
  1. public class TaskExecutorWebServer { 
  2.   private static final int NTHREADS = 100; 
  3.   private static final Executor exec = Executors.newFixedThreadPool(NTHREADS); 
  4.   public static void main(String[] args) throws Exception { 
  5.     ServerSocket serverSocket = new ServerSocket(80); 
  6.     while (true) { 
  7.       final Socket conn = serverSocket.accept(); 
  8.       Runnable task = new Runnable() { 
  9.         @Override 
  10.         public void run() { 
  11.           handleRequest(conn); 
  12.         } 
  13.       }; 
  14.       exec.execute(task); 
  15.     } 
  16.   } 

另外可以自己實現 Executor 來控制是並發還是並行的,如下面代碼:

 
  1. /** 
  2. * 執行已提交的 Runnable 任務的對象。 
  3. * 此介面提供一種將任務提交與每個任務將如何啟動並執行機制包括線程使用的細節、調度等)分離開來的方法。 
  4. * 通常使用 Executor 而不是顯式地建立線程。 
  5. * @author renchunxiao 
  6. */ 
  7. public class ExecutorDemo { 
  8.   public static void main(String[] args) { 
  9.     Executor executor = new ThreadExecutor(); 
  10.     executor.execute(new Runnable() { 
  11.       @Override 
  12.       public void run() { 
  13.         // do something 
  14.       } 
  15.     }); 
  16.     Executor executor2 = new SerialExecutor(); 
  17.     executor2.execute(new Runnable() { 
  18.       @Override 
  19.       public void run() { 
  20.         // do something 
  21.       } 
  22.     }); 
  23.   } 
  24. /** 
  25. * 建立一個線程來執行 command 
  26. * @author renchunxiao 
  27. */ 
  28. class ThreadExecutor implements Executor { 
  29.   @Override 
  30.   public void execute(Runnable command) { 
  31.     new Thread(command).start(); 
  32.   } 
  33. /** 
  34. * 串列執行 command 
  35. * @author renchunxiao 
  36. */ 
  37. class SerialExecutor implements Executor { 
  38.   @Override 
  39.   public void execute(Runnable command) { 
  40.     command.run(); 
  41.   } 

線程池

線程池就是線程的資源集區,可以通過 Executors 中的靜態Factory 方法來建立線程池。

  • newFixedThreadPool。建立固定長度的線程池,每次提交任務建立一個線程,直到達到線程池的最大數量,線程池的大小不再變化。

  • newSingleThreadExecutor。單個線程池。

  • newCachedThreadPool。根據任務規模變動的線程池。

  • newScheduledThreadPool。建立固定長度的線程池,以延遲或定時的方式來執行任務。

JVM 只有在所有非守護線程全部終止後才會退出,所以,如果無法正確的關閉 Executor,那麼 JVM 就無法結束。

為瞭解決執行服務的生命週期問題,有個擴充 Executor 介面的新介面 ExecutorService。

 
  1. public interface ExecutorService extends Executor { 
  2.   void shutdown(); 
  3.   List<Runnable> shutdownNow(); 
  4.   boolean isShutdown(); 
  5.   boolean isTerminated(); 
  6.   boolean awaitTermination(long timeout, TimeUnit unit) 
  7.     throws InterruptedException; 
  8.   <T> Future<T> submit(Callable<T> task); 
  9.   <T> Future<T> submit(Runnable task, T result); 
  10.   Future<?> submit(Runnable task); 
  11.   <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) 
  12.     throws InterruptedException; 
  13.   <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, 
  14.                   long timeout, TimeUnit unit) 
  15.     throws InterruptedException; 
  16.   <T> T invokeAny(Collection<? extends Callable<T>> tasks) 
  17.     throws InterruptedException, ExecutionException; 
  18.   <T> T invokeAny(Collection<? extends Callable<T>> tasks, 
  19.           long timeout, TimeUnit unit) 
  20.     throws InterruptedException, ExecutionException, TimeoutException; 

ExecutorService 生命週期有三種狀態:運行、關閉、已終止。ExecutorService 在初始建立時處於運行狀態。shutdown 方法會平緩關閉:不在接受新的任務,並且等待已經執行的任務執行完成(包括那些還未開始的任務)。shutdownNow 方法將粗暴關閉:它將嘗試取消所有運行中的任務,並且不再啟動隊列中尚未開始的任務。所有任務都執行完成後進入到已終止狀態。

Callable 和 Future

Executor 架構使用 Runnable 作為基本的任務表示形式。Runnable 是一種有局限性的抽象,它的 run 方法不能傳回值和拋出一個受檢查異常。

許多任務實際上是存在延時的計算,例如資料庫查詢,從網路擷取資源。對於這些任務,Callable 是更好的抽象,它認為 call 將返回一個值,並且可能拋出異常。

Executor 執行的任務有四個生命週期階段:建立、提交、開始和完成。由於有些任務需要很長時間有可能希望取消,在 Executor 架構當中,已提交未開始的任務可以取消。

Future 表示一個任務的生命週期,並且提供了相應的方法來判斷是否已經完成或取消,以及擷取任務的結果和取消任務等。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.