2016-04-15 50 views
1

我運行帶有嵌入式Jetty的jar。有時候會發生這樣的情況:一個請求陷入了一個無限循環。顯然固定無限循環將是最好的選擇。但是,目前這是不可能的。嵌入式碼頭,在給定時間後終止請求

所以,我正在尋找一個選項,檢查是否有一個請求存在超過例如。 5分鐘,並殺死相應的線程。

我嘗試了典型的碼頭選項:

  • maxIdleTime
  • soLingerTime
  • stopTimeout

他們沒有發揮預期。還有其他選擇需要考慮嗎?

回答

1

您是否可以訪問需要花費很長時間才能完成的代碼的代碼?如果是這樣你可以使用callable和一個Executor來實現這一點,下面是一個例子的單元測試:

@Test 
public void timerTest() throws Exception 
{ 
    //create an executor 
    ExecutorService executor = Executors.newFixedThreadPool(10); 

    //some code to run 
    Callable callable =() -> { 
    Thread.sleep(10000); //sleep for 10 seconds 
    return 123; 
    }; 

    //run the callable code 
    Future<Integer> future = (Future<Integer>) executor.submit(callable); 

    Integer value = future.get(5000, TimeUnit.MILLISECONDS); //this will timeout after 5 seconds 

    //kill the thread 
    future.cancel(true); 

} 
+0

感謝您的回答。使用未來是一個好主意。我希望有一個碼頭解決方案。由於碼頭也處理線程。 – Robin