Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CompletableFuture demo
public class CompletableFutureTest {
static class User {
private String nickname;
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
}
public User findUser() {
return new User();
}
private void update(User user) {
user.setNickname("haha");
System.out.println("update to db");
}
private void es(User user) {
System.out.println("save to es");
}
private void cache(User user) {
System.out.println("cache ...");
}
public void test() throws ExecutionException, InterruptedException {
CompletableFuture.supplyAsync(this::findUser)
.thenCompose(user -> {
if (user == null) {
throw new IllegalArgumentException("userInfoVO error");
}
return CompletableFuture.supplyAsync(() -> user);
})
.exceptionally(ex -> {
System.out.println(ex);
return null;
})
.thenApplyAsync(user -> {
System.out.println("thenApplyAsync update");
if (user != null) {
update(user);
}
return user;
})
.thenApplyAsync(user -> {
System.out.println("thenApplyAsync es");
if (user != null) {
es(user);
}
return user;
})
.thenApplyAsync(user -> {
System.out.println("thenApplyAsync cache");
if (user != null) {
cache(user);
}
return user;
}).get();
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
new CompletedFutureTest().test();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.