Java Magazine, Sept/Oct 2017
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2017 40 java 9 timeoutAfter 1 TimeUnit SECONDS amount System out println The price is amount GBP A simple implementation of timeoutAfter is as follows where the variable delayer stores an instance of a ScheduledThreadPoolExecutor public T CompletableFuture T timeoutAfter long timeout TimeUnit unit CompletableFuture T result new CompletableFuture T delayer schedule result completeExceptionally new TimeoutException timeout unit return result The timeoutAfter method will return a CompletableFuture which schedules a TimeoutException after a specified time You can then use it in combination with the method acceptEither to select whichever CompletableFuture is first to complete the actual service or the timeout Unfortunately as you can see the implementation requires you to write a lot of code Java 9 improvements Java 9 s CompletableFuture introduces several new methods Among them are orTimeout and completeOnTimeOut which provide built in support for dealing with timeouts so you dont need to implement them yourself The method orTimeout has the following signature public CompletableFuture T orTimeout long timeout TimeUnit unit
You must have JavaScript enabled to view digital editions.