Handle InterruptedException

Reference


How to handle InterruptedException

  • Throw it directly
  • If you can't throw it, call Thread.currentThread().interrupt()
  • Check Thread.currentThread().isInterrupted() every while loop if you catch an InterruptedException within the loop block

Example:

This example shows how to handle InterruptedException, you can change code to check what will happen in other cases.
public class TestMain {

 public static void main(String[] params) {
  ThreadPoolExecutor e = (ThreadPoolExecutor) Executors.newCachedThreadPool();
  MyRunnable r = new MyRunnable();
  e.execute(r);
  System.out.println("shutdown");
  e.shutdownNow();
  System.out.println("shutdown done");
 }

 private static class MyRunnable implements Runnable {

  @Override
  public void run() {
   while (!Thread.currentThread().isInterrupted()) {
    try {
     System.out.println("sleep");
     TimeUnit.HOURS.sleep(1);
    } catch (InterruptedException e) {
     e.printStackTrace();
     Thread.currentThread().interrupt();
    }
   }
  }
 }

}

別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...