1

Considering the following code:

@RestController
@RequestMapping("/requestLimit")
public class TestController {

    @Autowired
    private TestService service;

    @GetMapping("/max3")
    public String max3requests() {
        return service.call();
    }
}

@Service
public class TestService {

    public String call() {
        //some business logic here
        return response;
    }
}

What i want to accomplish is that if the method call from the TestService is being executed by 3 threads at the same time, the next execution generate a response with a HttpStatus.TOO_MANY_REQUESTS code.

3
  • You have to keep a Atomic variable and increment in your controller class. Increment it in your method and check if it exceeds 3 and if yes return else proceed Commented Aug 30, 2018 at 14:03
  • Thanks @pvpkiran, with your recomendation I managed to propose an answer Commented Aug 30, 2018 at 14:40
  • Use a Semaphore Which is designed for this. Commented Aug 30, 2018 at 19:10

1 Answer 1

2

Thanks to @pvpkiran comment I managed to code this:

@RestController
@RequestMapping("/requestLimit")
public class TestController {

    private final AtomicInteger counter = new AtomicInteger(0);

    @Autowired
    private TestService service;

    @GetMapping("/max3")
    public String max3requests() {
        while(true) {
            int existingValue = counter.get();
            if(existingValue >= 3){
                throw new TestExceedRequestLimitException();
            }
            int newValue = existingValue + 1;
            if(counter.compareAndSet(existingValue, newValue)) {
                return service.call();
            }
        }
    }
}

@Service
public class TestService {

    public String call() {
        //some business logic here
        return response;
    }
}

With the corresponding exception definition:

@ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
public class TestExceedRequestLimitException extends RuntimeException{ }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.