Unlock Java Distributed Locks with Lock4j: Guide & Advanced Tips

This article introduces Lock4j, a Java distributed lock library supporting RedisTemplate, Redisson, and Zookeeper, walks through its key features, dependency setup, configuration, annotation attributes, simple and advanced usage examples, and demonstrates custom executors, key builders, and failure strategies for robust concurrency control.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Unlock Java Distributed Locks with Lock4j: Guide & Advanced Tips

Introduction

Lock4j is a distributed lock component for Java that offers multiple backend support such as RedisTemplate, Redisson, and Zookeeper, and can be used declaratively via Spring AOP annotations or programmatically.

Features

Simple to use, powerful, highly extensible.

Supports Redisson, RedisTemplate, Zookeeper; can be mixed and extended.

Preparation

Include the appropriate Maven dependency according to the lock implementation you plan to use. <!-- Maven dependency XML placeholder --> Configure Redis connection parameters in application.yml (or application.properties).

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 the endpoint repeatedly (e.g., http://localhost:8080/mock/lockMethod?key=123) to see lock acquisition success or failure.

Advanced Usage

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 in the annotation: @Lock4j(executor = CustomRedissonLockExecutor.class).

Custom Key Builder

@Component
public class CustomKeyBuilder extends DefaultLockKeyBuilder {

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

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

Manual Lock and Release

@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 logo
Lock4j logo
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.

JavaconcurrencyRedisSpring Bootdistributed lockLock4j
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.