Reputation: 4402
We have a Spring Boot service like this:
@Service
public class XXXDataService {
public XXXModel resolveData(){
}
}
The resolveData
method fetches data from a datasource and returns it. In general it can handle several threads asking for data at the same time. But not more then n
threads at the same time.
Is there a Spring-build-in solution to restrict the number of threads accessing a method.
Something like @Synchronized(maxParallelAccesses=10)
.
Hint 1: It is important that all the other Spring interceptors are also not fired
, for example a transaction should not be started until the method is not blocked anymore.
Hint 2: I don't wan't to restrict the overall number of threads of the application but only having some kind of method synchronization with size > 1.
Upvotes: 3
Views: 1208
Reputation: 3285
I don't think Spring or even Java provides a build-in annotation to do that. But that logic can be implemented with a Semaphore
:
@Service
public class XXXDataService {
private Semaphore semaphore = new Semaphore(10);
public XXXModel resolveData(){
semaphore.acquire();
//... logic accessible by max 10 threads concurrently
semaphore.release();
}
}
Upvotes: 1