Method Lock (Java Spring library)

There are many situations where a particular method needs to be executed at a time by just one thread or http request.

For example it’s common that scheduled tasks in our project be executed at most once at the same time. If a task is being executed on one node, it acquires a lock that prevents execution of the that task from another thread or another node in clustering.

Another situation is when we need to lock a particular method with its input or parameters.

for example imagine we have an API that receive userId and foodId and do something in the backend. It’s important to lock API just for specific combination of userId and foodId and if another request with the same parameters received in that node or any other node in cluster, the method be locked and does not process new requests.

I created an open-source java library it exists in GitHub. this library is based on spring framework AOP.

To lock a method just need to put an annotation @Lock to that method and set locking parameters of it and DONE!

This library use a caching interface that you can implementing it yourself, or just use one of the provided implementations, in-memory, Redis, Redis cluster.


class Request{
String userId;
String foodId;

@Lock(type = "ORDER_FOOD", params = {"#request.userId","#request.foodId"}, timeoutSec = 4)
public ResponseDto<Void> lock(Request request) {
class A{
B b;
class B{
long id;

@Lock(type = "SOMETHING", params = "#list.![]")
public ResponseDto<Void> lockList(List<A> list) {
return null;
@PostMapping(value = "lockList22")
@Lock(type = "SOMETHING", params = {"#c.list.![]","#param", "#param2"})
public ResponseDto<Void> lockList2(@RequestBody @Validated C c, @RequestParam Long param, @RequestParam Long param2) {
return null;
@Lock(type = "JUST-BY-TYPE")
public ResponseDto<Void> lockList2(Long param, Long param2) {
return null;

please see GitHub repository, rate and share it and help us to contribute it :)

Java Developer