Lock on ListenableFuture with timeout

I am using Spring 4.2.3 AsyncRestTemplate.exchange () to call some API that will take a few seconds, and I expect listenableFuture.get (1, TimeUnit.SECONDS) to block for 1 second and then throw a TimeOutException.

Instead, what happens is that listenableFuture.get () will block the entire api call (more than 1 second)

AsyncRestTemplate restTemplate = new AsyncRestTemplate(); ListenableFuture<ResponseEntity<String>> listenableFuture = restTemplate.exchange(URL, HttpMethod.GET, null, String.class); log.debug("before callback"); //...add callbacks try{ log.debug("before blocking"); listenableFuture.get(1, TimeUnit.SECONDS); }catch (InterruptedException e) { log.error(":GOT InterruptedException"); } catch (ExecutionException e) { log.error(":GOT ExecutionException"); } catch (TimeoutException e) { log.info(":GOT TimeoutException"); } log.info("FINISHED"); 

Output:

  09:15:21.596 DEBUG [main] org.springframework.web.client.AsyncRestTemplate:78 - Created asynchronous GET request for "http://localhost:4567/oia/wait?seconds=5" 09:15:21.666 DEBUG [main] org.springframework.web.client.RestTemplate:720 - Setting request Accept header to [text/plain, application/xml, text/xml, application/json, application/*+xml, application/*+json, */*] 09:15:21.679 DEBUG [main] com.zazma.flow.utils.FutureTest:74 - before callback 09:15:21.679 DEBUG [main] com.zazma.flow.utils.FutureTest:95 - before blocking 09:15:26.709 DEBUG [main] org.springframework.web.client.AsyncRestTemplate:576 - Async GET request for "http://localhost:4567/oia/wait?seconds=5" resulted in 200 (OK) 09:15:26.711 DEBUG [main] org.springframework.web.client.RestTemplate:101 - Reading [java.lang.String] as "text/html;charset=utf-8" using [ org.springframework.http.converter.StringHttpMessageConverter@3a 44431a] 09:15:26.717 INFO [main] com.zazma.flow.utils.FutureTest:105 - FINISHED 

Here is an example that ListenableFuture.get () will work as expected if AsyncRestTemplate is not created

 SimpleAsyncTaskExecutor te = new SimpleAsyncTaskExecutor(); ListenableFuture<String> lf = te.submitListenable(() -> { Thread.sleep(8000); return "OK"; }); lf.get(1, TimeUnit.SECONDS); 
+5
source share
1 answer

You code the code correctly. As a result of the problem, an error occurs in the spring structure. Although I was not able to find it in the spring tracker issue (or perhaps it is not documented), you can fix it by updating the dependencies. Of course, your code will work with spring -web> = 4.3.2.RELEASE version.

+1
source

Source: https://habr.com/ru/post/1264288/


All Articles