2016-04-15 51 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