/*** 同步批量同意好友请求*/
List<User> confirmAddAllFriends(long uid) {List<User> result = new ArrayList<>();for (long friend : getAllAppliedFriendList()) {if (getUserCurrentFriendsCount(uid) >= MAX_FRIENDS_SIZE) {break;}if (getUserCurrentFriendsCount(friend) >= MAX_FRIENDS_SIZE) {continue;}addFriend(friend, uid);addFriend(uid, friend);removeFromAppliedList(uid, friend);}return result;
}
/*** 批量同意好友请求,由于对方数据可能需要异步转发操作,整体需要改造成异步函数*/
CompletableFuture<List<User>> confirmAddAllFriendsAsync(long uid) {List<User> result = new ArrayList<>();Iterator<Long> iterator = getAllAppliedFriendList.iterator();return asyncIterator(result, uid, iterator);
}/*** 异步确认好友请求*/
@Forward(ForwardToUserServer.class) // 可能涉及跨服代理转发
CompletableFuture<User> addFriendConfirmedAsync(long confirmedUid, long initiatorUid) {User user = getUser(confirmedUid);if (user == null || getUserCurrentFriendsCount(confirmedUid) >= MAX_FRIENDS_SIZE) {return CompletableFuture.completedFuture(null);}addFriend(confirmedUid, initiatorUid);return CompletableFuture.completedFuture(user);
}/*** 异步迭代器*/
CompletableFuture<List<User>> asyncIterator(List<User> result, long uid, Iterator<Long> iterator) {if (iterator.hasNext()) {long friend = iterator.next();if (getUserCurrentFriendsCount(uid) >= MAX_FRIENDS_SIZE) {return CompletableFuture.completedFuture(result);}return addFriendConfirmedAsync(targetUid, uid).thenCompose(user -> {if (user != null) {addFriend(uid, friend);removeFromAppliedList(uid, friend);result.add(user);}return asyncIterator(result, uid, iterator);});}return CompletableFuture.completedFuture(result);
}
异步迭代器,Java的CompletableFuture
构造扁平化树状依赖(链表)并利用CompletionStage
局部状态机,来组织全局依赖关系并控制状态流转,Rust的Future
直接编译构造状态机,来组织依赖关系并控制状态流转。