简体   繁体   中英

abandon execution of a method after 3 seconds

I've this method:

public ResponseDTO getManh(QueryDTO manhQueryDTO) {
  return requestHttpService.post(ManhQueryResponseDTO.class,
                    uri(properties.getManhattan().getUrl(), REQUEST_QUERY), manhQueryDTO);
}

I need abandon execution of a method after 3 seconds.

does anyone have any idea what to do?

I create a object only to control this call - tryTimeout().

    ResponseDTO responseDTO = tryTimeout();

this is the control obj:

  private ResponseDTO tryTimeout() {

    final Duration timeout = Duration.ofSeconds(1);
    ExecutorService executor = Executors.newSingleThreadExecutor();

    final Future<ResponseDTO> handler = executor.submit(new Callable() {
        @Override
        public ResponseDTO call() throws Exception {
            return origin.serviceToCall();
        }
    });

    try {
        return handler.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {

        LOGGER.error("TIMEOUT");

    } finally {
        executor.shutdown();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM