有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java嵌入Jetty,在给定时间后终止请求

我运行一个带有嵌入式码头的罐子。有时,一个请求会陷入无休止的循环。显然,修复无休止的循环是最好的选择。然而,这目前是不可能的

所以我在寻找一个选项,它检查一个请求是否存在超过5分钟,并终止相应的线程

我尝试了典型的码头选择:

  • 最大空闲时间
  • soLingerTime
  • 停止超时

他们都没有按预期工作。还有另一个选择要考虑吗?


共 (1) 个答案

  1. # 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);
    
    }