Master Distributed Locks in Java with Lock4j: Features, Setup, and Advanced Usage

This article introduces the Lock4j distributed lock library for Java, outlines its key features and supported backends, provides step‑by‑step Maven dependency setup, Redis configuration, annotation details, and demonstrates both basic and advanced usage patterns including custom executors and lock‑failure strategies.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Master Distributed Locks in Java with Lock4j: Features, Setup, and Advanced Usage

1. Introduction

Lock4j is a distributed lock component that offers multiple implementations (Spring AOP‑based declarative and programmatic locks) and supports RedisTemplate , Redisson , and Zookeeper .

2. Features

Simple to use, powerful functionality, strong extensibility.

Supports redisson, redisTemplate, zookeeper; can be mixed and extended.

Gitee address: https://gitee.com/baomidou/lock4j

3. Preparation

3.1 Add Maven dependencies

<!-- Lock4j -->
<!-- If using redisTemplate as the lock backend -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>lock4j-redis-template-spring-boot-starter</artifactId>
    <version>2.2.4</version>
</dependency>
<!-- If using redisson as the lock backend -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>lock4j-redisson-spring-boot-starter</artifactId>
    <version>2.2.4</version>
</dependency>

3.2 Redis configuration

spring:
  redis:
    database: 0
    # Redis server address
    host: 127.0.0.1
    # Redis server port
    port: 6379
    # Password (empty by default)
    password:
    jedis:
      pool:
        max-active: 200
        max-wait: -1
        max-idle: 10
        min-idle: 0
    timeout: 6000

4. Annotation attributes

package com.baomidou.lock.annotation;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Lock4j {
    String name() default "";
    Class<? extends LockExecutor> executor() default LockExecutor.class;
    String[] keys() default {""};
    long expire() default -1L;
    long acquireTimeout() default -1L;
    boolean autoRelease() default true;
}

5. Simple usage

@RestController
@RequestMapping("/mock")
public class MockController {

    @GetMapping("/lockMethod")
    @Lock4j(keys = {"#key"}, acquireTimeout = 1000, expire = 10000)
    public Result lockMethod(@RequestParam String key) {
        ThreadUtil.sleep(5000);
        return Result.OK(key);
    }
}

Access the endpoint repeatedly, e.g. http://localhost:8080/mock/lockMethod?key=123. When the lock is acquired the response is:

{
    "success": true,
    "message": "操作成功!",
    "code": 200,
    "result": "123",
    "timestamp": 1678866083211
}

If the lock cannot be obtained, Lock4j throws com.baomidou.lock.exception.LockFailureException, which can be handled globally to return:

{
    "success": false,
    "message": "操作失败,request failed,please retry it.",
    "code": 500,
    "result": null,
    "timestamp": 1678866034929
}

6. Advanced usage

6.1 Custom executor

/**
 * Custom distributed lock executor
 */
@Component
public class CustomRedissonLockExecutor extends AbstractLockExecutor {

    @Override
    public Object acquire(String lockKey, String lockValue, long expire, long acquireTimeout) {
        return null;
    }

    @Override
    public boolean releaseLock(String key, String value, Object lockInstance) {
        return false;
    }
}

Specify the executor on the annotation: @Lock4j(executor = CustomRedissonLockExecutor.class).

6.2 Custom key builder

/**
 * Custom distributed lock key generator
 */
@Component
public class CustomKeyBuilder extends DefaultLockKeyBuilder {

    public CustomKeyBuilder(BeanFactory beanFactory) {
        super(beanFactory);
    }
}

6.3 Custom lock‑failure strategy

/**
 * Custom strategy when lock acquisition fails
 */
@Component
public class GrabLockFailureStrategy implements LockFailureStrategy {

    @Override
    public void onLockFailure(String key, Method method, Object[] arguments) {
        // custom handling
    }
}

The default failure strategy is com.baomidou.lock.DefaultLockFailureStrategy.

6.4 Manual lock and unlock

@Service
public class LockServiceImpl implements LockService {

    @Autowired
    private LockTemplate lockTemplate;

    @Override
    public void lock(String resourceKey) {
        LockInfo lock = lockTemplate.lock(resourceKey, 10000L, 2000L, CustomRedissonLockExecutor.class);
        if (lock == null) {
            throw new FrameworkException("业务处理中,请稍后再试...");
        }
        try {
            doBusiness();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lockTemplate.releaseLock(lock);
        }
    }

    private void doBusiness() {
        // TODO business logic
    }
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaRedisdistributed lockspring-aopLock4j
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.