I have this piece of code:
final Future<ApplicationUser> user = applicationUserService.findIncludePrivilegesById(id);
while (!user.isDone()) {
Thread.sleep(100);
}
if (user.get() == null) throw new Exception(this.getMessageSource().getMessage("label.error.findError",
null, locale));
model.addAttribute("user", new ApplicationUserDto(user.get()));
model.addAttribute("roles", Role.valuesMinusApi());
model.addAttribute("groups", completeAuthorityList);
model.addAttribute("message", this.getMessageSource().getMessage("label.dialog.userEdit", new Object[]{user.get().getLogin()}, locale));
model.addAttribute("applicationUserStates", ApplicationUserState.values());
return "administration/edit";
applicationUserService.findIncludePrivilegesById(id)
方法会去远程数据库服务器查询数据。我在设计这段代码时的想法是通过使用 async 让这个耗时的数据库通信处理一个自由线程池中的线程。 就我所理解的整个
async
过程,可能会出现以下步骤:
- 主线程进入方法
- 线程池中的一个线程查询数据
- 主线程等待或拥有剩余资源来做“其他”事情
- 如果线程池线程完成了任务,我可以使用它的结果
使用
Thread.sleep()
是好的实践吗?我唯一能想象到的好处是,当线程池线程执行耗时操作时,主线程是自由的(未被阻塞),可以处理其他计算(也许是处理其他Web请求)。
Future
相比,CF
更可取,并且 Spring 可以在 某些情况下 自动利用它。该指南展示了一种更清晰的编写代码的方式,类似于您所拥有的实际并行工作(您没有)。难点在于知道何时使用异步方法。该指南具有我描述的相同的合成示例:多个缓慢的调用。除非您正在处理遗留代码,否则您需要修复为什么这些调用需要如此长时间。因此,请阅读该指南以获取技术细节,而不是设计或使用指南。 - Kayaman