Java: set timeout on a certain block of code?

前端 未结 11 1014
终归单人心
终归单人心 2020-11-27 03:45

Is it possible to force Java to throw an Exception after some block of code runs longer than acceptable?

11条回答
  •  隐瞒了意图╮
    2020-11-27 04:12

    If you want a CompletableFuture way you could have a method like

    public MyResponseObject retrieveDataFromEndpoint() {
    
       CompletableFuture endpointCall 
           = CompletableFuture.supplyAsync(() ->
                 yourRestService.callEnpoint(withArg1, withArg2));
    
       try {
           return endpointCall.get(10, TimeUnit.MINUTES);
       } catch (TimeoutException 
                   | InterruptedException 
                   | ExecutionException e) {
           throw new RuntimeException("Unable to fetch data", e);
       }
    }
    

    If you're using spring, you could annotate the method with a @Retryable so that it retries the method three times if an exception is thrown.

提交回复
热议问题