Skip to content
Advertisement

Spring controller how to serve only 1 request each time, and discard other requests received for the same method until first request has finished

So as the title describes I want to achieve the following

JavaScript

I want the code to be executed only for 1 request that comes at a time. The execution of the code inside the synchronized block can last about 1 hour. In the mean time I would like each other request that arrives to that method to be cancelled. Is there any way to achieve that?

Just to clarify:

As it is right now the first request will be served and when it finishes the next request that was waiting for the lock will be served and then the next that was waiting.

What I want is to not allow other requests which are already waiting to be served after the first request finishes. If the requests came during the execution of the first request I want to return bad request or something else to the user and to cancel their request.

Advertisement

Answer

Approach 1:

Use a single permit Semaphore

Here’s a sample code:

JavaScript

Approach 2:

Use a ReentrantLock

Sample Code:

JavaScript

Driver:

JavaScript

(one of the) Output (s):

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement