Apply timeout control around Java operation

前端 未结 7 877
滥情空心
滥情空心 2021-02-07 06:54

I\'m using a third party Java library to interact with a REST API. The REST API can sometimes take a long time to respond, eventually resulting in a java.net.ConnectExcept

7条回答
  •  独厮守ぢ
    2021-02-07 07:25

    This is probably the current way how this should be done with plain Java:

    public String getResult(final RESTService restService, String url) throws TimeoutException {
        // should be a field, not a local variable
        ExecutorService threadPool = Executors.newCachedThreadPool();
    
        // Java 8:
        Callable callable = () -> restService.getResult(url);
    
        // Java 7:
        // Callable callable = new Callable() {
        //     @Override
        //     public String call() throws Exception {
        //         return restService.getResult(url);
        //     }
        // };
    
        Future future = threadPool.submit(callable);
        try {
            // throws a TimeoutException after 1000 ms
            return future.get(1000, TimeUnit.MILLISECONDS);
        } catch (ExecutionException e) {
            throw new RuntimeException(e.getCause());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new TimeoutException();
        }
    }
    

提交回复
热议问题