Created
November 3, 2018 02:50
-
-
Save vamdt/474a6de9a5c4acf9e07ad64a76eb73b2 to your computer and use it in GitHub Desktop.
CompletableFuture demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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