import lombok.extern.slf4j.Slf4j;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author CW
* @ClassName LockUtil.java
* @createTime 2023年02月09日 16:24:00
*/
@Slf4j
public class LockUtil {
private final static Map<String, Lock> map = new ConcurrentHashMap();
private final static Map<String, Lock> map2 = new ConcurrentHashMap();
public final static String SAVE_DTU_LOCK = "SAVE_DTU_LOCK:";
/**
* 细粒度lock,自定义 MyReentrantLock,会清理map中的lock
* 若不清理lock对象,可能会导致内存溢出的情况,
*
* @param granular 冲突粒度,据此判断是否创建新lock对象
* @author XHS-2021
* @date 2022/7/2 16:56
* @return java.util.concurrent.locks.Lock
*/
public static Lock getLock(String granular){
Lock lock = map.get(granular);
if(lock != null){
return lock;
}else{
lock = map.putIfAbsent(granular, new MyReentrantLock(granular));
if(lock == null){
return getLock(granular);
}else{
return lock;
}
}
}
/**
* 【慎用】
* 粗粒度lock,不会清理map中lock,会一直累计,长久下去要考虑内存溢出的情况
*
* @param granular
* @author XHS-2021
* @date 2022/7/2 16:57
* @return java.util.concurrent.locks.Lock
*/
public static Lock getCoarseGrainLock(String granular){
Lock lock = map2.get(granular);
if(lock != null){
return lock;
}else{
lock = map2.putIfAbsent(granular, new ReentrantLock());
if(lock == null){
return getLock(granular);
}else{
return lock;
}
}
}
static class MyReentrantLock extends ReentrantLock{
String granular;
public MyReentrantLock(String granular) {
super();
this.granular = granular;
}
@Override
public void unlock() {
if(map.containsKey(granular)){
map.remove(granular);
try {
super.unlock();
} catch (IllegalMonitorStateException e) {
// log.error(e.getMessage(), e);
}
}
}
}
}
调用:
Lock lock = LockUtil.getLock(key);
if (lock.tryLock(10, TimeUnit.SECONDS)) {
try {
} finally {
lock.unlock();
}
}else{
throw new RuntimeException("失败,请重试!");
}
标签:map,return,lock,granular,内存,Lock,java From: https://www.cnblogs.com/cw828/p/17129921.html