public class CompleteOnTimeoutDemo { | |
public static void main(String[] args) { | |
CompletableFuture orTimeout = CompletableFuture.supplyAsync(() -> { | |
try { | |
return getUsers(); | |
} catch (Exception ex) { | |
System.out.println(ex.getMessage()); | |
return null; | |
} | |
}) | |
.completeOnTimeout(getUsersFallback(), 1, TimeUnit.SECONDS); | |
System.out.println(orTimeout.join()); | |
} | |
private static List getUsers() throws Exception { | |
// In this case fallback method will be invoked, if this value is lesser than 1000, i.e 1 second, it will invoke the service only. | |
Thread.sleep(2000); | |
List users = Arrays.asList("Deepak", "Ayush", "Nitesh", "Santosh", "Simran"); | |
return users; | |
} | |
private static List getUsersFallback() { | |
return Arrays.asList("Fallback List"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment