本地锁工具类

2023-05-18 14:21:24 浏览数 (1)

起步依赖

代码语言:javascript复制
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>2.9.3</version>
</dependency>

LockUtil

代码语言:javascript复制
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 本地锁工具类,每个key一把锁
 */
public class LockUtil {

    private LockUtil() {
        throw new IllegalStateException("工具类禁止实例化");
    }

    /**
     * 线程安全,5分钟过期
     */
    private static final Cache<String, ReentrantLock> LOCK_CACHE = Caffeine.newBuilder()
            .expireAfterAccess(10, TimeUnit.MINUTES)
            .maximumSize(1000)
            .build();

    /**
     * 获取锁实例
     * 如果key不存在则新建ReentrantLock
     *
     * @param key key
     * @return Lock
     */
    public static ReentrantLock getLock(String key) {
        return LOCK_CACHE.get(key, lock->newLock());
    }

    /**
     * 新建锁
     *
     * @return ReentrantLock
     */
    private static ReentrantLock newLock(){
        return new ReentrantLock();
    }
}

0 人点赞