依靠ConcurrentHashMap特性,自己实现一个工厂类:
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@Slf4j
public class MutexFactory {
private static final String DEFAULT_KEY = "default";
/**
* 依靠ConcurrentHashMap的特性来实现互斥
**/
private static ConcurrentMap<String, Mutex> globalMutexMap = new ConcurrentHashMap<>();
private MutexFactory() {
}
public static Mutex getMutex(String key) {
String finalKey = handleKey(key);
return globalMutexMap.compute(key, (k, v) -> (v == null) ? new Mutex(finalKey) : v);
}
private static String handleKey(String key) {
if (StringUtils.isEmpty(key)) {
return DEFAULT_KEY;
} else {
return key;
}
}
@Data
static class Mutex {
private String value;
public Mutex(String value) {
this.value = value;
}
}
}
使用:
synchronized (MutexFactory.getMutex(key)){
System.out.println("handle:" +key);
}
标签:ConcurrentHashMap,String,synchronized,private,互斥,static,key,import From: https://www.cnblogs.com/xfeiyun/p/17797077.html