Skip to content

Instantly share code, notes, and snippets.

@vamdt
Created November 3, 2018 02:50
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 vamdt/474a6de9a5c4acf9e07ad64a76eb73b2 to your computer and use it in GitHub Desktop.
Save vamdt/474a6de9a5c4acf9e07ad64a76eb73b2 to your computer and use it in GitHub Desktop.
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