user14857007
user14857007

Reputation:

Spring Boot Rest-Controller restrict multithreading

I want my Rest Controller POST Endpoint to only allow one thread to execute the method and every other thread shall get 429 until the first thread is finished.

    @ResponseStatus(code = HttpStatus.CREATED)
    @PostMapping(value ="/myApp",consumes="application/json",produces="application/json")
    public Execution execute(@RequestBody ParameterDTO StartDateParameter)  
    {
        if(StartDateParameter.getStartDate()==null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
        }else {
            if(Executer.isProcessAlive()) {
                throw new ResponseStatusException(HttpStatus.TOO_MANY_REQUESTS);
            }else {
                return Executer.execute(StartDateParameter);
            }       
        }
    }

When I send multithreaded requests, every request gets 201. So I think the requests get in earlier than the isAlive() method beeing checked. How can I change it to only process the first request and "block" every other?

Upvotes: 0

Views: 1205

Answers (1)

Superchamp
Superchamp

Reputation: 146

Lifecycle of a controller in spring is managed by the container and by default, it is singleton, which means that there is one instance of the bean created at startup and multiple threads can use it. The only way you can make it single threaded is if you use a synchronized block or handle the request call through an Executor service. But that defeats the entire purpose of using spring framework.

Spring provides other means to make your code thread safe. You can use the @Scope annotation to override the default scope. Since you are using a RestController, you could use the "request" scope (@Scope("request")), which creates a new instance to process your every http request. Doing it this way will make ensure that only 1 thread will be accessing your controller code at any given time.

Upvotes: 1

Related Questions