Master Distributed Locking in Java with Lock4j: A Complete Guide

This article introduces Lock4j, a versatile Java distributed‑lock component supporting RedisTemplate, Redisson and Zookeeper, explains its key features, shows how to add dependencies and configure Redis, details the @Lock4j annotation attributes, provides simple and advanced usage examples with code snippets, and demonstrates custom executors, key builders, failure strategies, and manual lock handling.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Master Distributed Locking in Java with Lock4j: A Complete Guide

Introduction

Lock4j is a distributed lock component that offers multiple back‑ends such as RedisTemplate, Redisson and Zookeeper, supporting both declarative (Spring AOP) and programmatic locking.

Features

Simple to use, powerful and highly extensible.

Supports Redisson, RedisTemplate, Zookeeper and can be mixed.

Prerequisites

3.1 Add 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 Add Redis Configuration

spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password:
    jedis:
      pool:
        max-active: 200
        max-wait: -1
        max-idle: 10
        min-idle: 0
    timeout: 6000

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;
}

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 http://localhost:8080/mock/lockMethod?key=123. If 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: request failed,please retry it.

and a global exception handler can return:

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

Advanced Usage

6.1 Custom 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

@Component
public class CustomKeyBuilder extends DefaultLockKeyBuilder {
    public CustomKeyBuilder(BeanFactory beanFactory) {
        super(beanFactory);
    }
}

6.3 Custom Lock Failure Strategy

@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/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();
        } finally {
            lockTemplate.releaseLock(lock);
        }
    }

    private void doBusiness() {
        // business logic
    }
}
Lock4j diagram
Lock4j diagram
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.

javaredisSpring BootLock4j
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

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.