I'm new to Spring MVC and I didn't find anything about this in doc.
Let's say I have a controller /accounts which accepts POST requests to create an account.
Two requests comes (almost) in the same time with the same account id.
ASFAIK dispatcherServlet
manages the requests.
Is the 2nd request put in queue until the first one has been completed?
Or there would be two threads working with two requests simultaneously?
UPDATE:
Check the official Spring tutorial: Building a REST service.
There is controller with method add
:
@RequestMapping(method = RequestMethod.POST)
ResponseEntity<?> add(@PathVariable String userId, @RequestBody Bookmark input) {
this.validateUser(userId);
return this.accountRepository
.findByUsername(userId)
.map(account -> {
Bookmark result = bookmarkRepository.save(new Bookmark(account,
input.uri, input.description));
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(ServletUriComponentsBuilder
.fromCurrentRequest().path("/{id}")
.buildAndExpand(result.getId()).toUri());
return new ResponseEntity<>(null, httpHeaders, HttpStatus.CREATED);
}).get();
}
Controllers are just beans, by default they are singleton.
When two simultaneous requests are received the same instance of the controller is used by two threads. Let's imagine the 1st thread already saved new bookmark and executing
httpHeaders.setLocation(ServletUriComponentsBuilder
.fromCurrentRequest().path("/{id}")
.buildAndExpand(result.getId()).toUri());
Meanwhile the 2nd thread just executed
Bookmark result = bookmarkRepository.save(new Bookmark(account,
input.uri, input.description));
In this case the first thread will return result.getId()).toUri()
which is created by the 2nd thread.
Is it correct workflow and is this controller thread-safe?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…