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";
The applicationUserService.findIncludePrivilegesById(id)
goes to a remote db server to query the data.
My thoughts on designing this piece of code were to let this (time consuming db communication) handle a free thread from the pool (by using async).
As far as i have understood the whole async
these steps may happen:
- Main thread enters the method
- A thread from the thread pool queries the data
- The main thread waits or has ressources left over to do "other" things
- If the thread pool thread is finished, i can use the results
Do i really profit from this scenario as i have to wait for the results in every case (calling the service method async of sync)?
Is it good practise to use Thread.sleep()
?
The only benefit i can imagine from this example is that the main thread is free (not blocked) for other computations (handling other web requests maybe) while the thread pool thread does the time consuming process?