Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

java - Is Spring Boot MVC controller multithreaded?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Most servlets start a separate thread for each incoming request and Spring isnt an exception to that. You need to make sure that the shared beans are thread safe. Otherwise Spring takes care of the rest.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...