Skip to content

Instantly share code, notes, and snippets.

@deepakmehra10
Created April 27, 2020 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deepakmehra10/8c06b3854607379c3804bcabda831bd6 to your computer and use it in GitHub Desktop.
Save deepakmehra10/8c06b3854607379c3804bcabda831bd6 to your computer and use it in GitHub Desktop.
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