首页 > > > 用String实现同步锁,你会吗?
阅读本文大概需要 4.2 分钟。
来自:https://dwz.cn/mzLNZTIm
public void method1() {
String str1 = "a";
synchronized (str1) {
// do sync a things...
}
}
public void method2() {
String str2 = "a";
synchronized (str2) {
// do sync b things...
}
}
public void method3() {
String str1 = "a";
synchronized (str1.intern()) {
// do sync a things...
}
}
public void method4() {
String str2 = "a";
synchronized (str2.intern()) {
// do sync b things...
}
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
/**
* 基于string 的锁实现
*/
public final class StringBasedMutexLock {
private static final Logger logger = LoggerFactory.getLogger(StringBasedMutexLock.class);
/**
* 字符锁 管理器, 将每个字符串 转换为一个 CountDownLatch
*
* 即锁只会发生在真正有并发更新 同一个 String 的情况下
*
*/
private static final ConcurrentMap<String, CountDownLatch> lockKeyHolder = new ConcurrentHashMap<>();
/**
* 基于lockKey 上锁,同步执行
*
* @param lockKey 字符锁
*/
public static void lock(String lockKey) {
while (!tryLock(lockKey)) {
try {
logger.debug("【字符锁】并发更新锁升级, {}", lockKey);
blockOnSecondLevelLock(lockKey);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.error("【字符锁】中断异常:" + lockKey, e);
break;
}
}
}
/**
* 释放 lockKey 对应的锁选项,使其他线程可执行
*
* @param lockKey 要使用互斥的字符串
* @return true: 释放成功, false: 释放失败,可能被其他线程误释放
*/
public static boolean unlock(String lockKey) {
// 先删除锁,再释放锁,此处会导致后续进来的并发优先执行,无影响
CountDownLatch realLock = getAndReleaseLock1(lockKey);
releaseSecondLevelLock(realLock);
return true;
}
/**
* 尝试给指定字符串上锁
*
* @param lockKey 要使用互斥的字符串
* @return true: 上锁成功, false: 上锁失败
*/
private static boolean tryLock(String lockKey) {
// 此处会导致大量 ReentrantLock 对象创建吗?
// 其实不会的,这个数量最大等于外部并发数,只是对 gc 不太友好,会反复创建反复销毁y
return lockKeyHolder.putIfAbsent(lockKey, new CountDownLatch(1)) == null;
}
/**
* 释放1级锁(删除) 并返回重量级锁
*
* @param lockKey 字符锁
* @return 真正的锁
*/
private static CountDownLatch getAndReleaseLock1(String lockKey) {
return lockKeyHolder.remove(lockKey);
}
/**
* 二级锁锁定(锁升级)
*
* @param lockKey 锁字符串
* @throws InterruptedException 中断时抛出异常
*/
private static void blockOnSecondLevelLock(String lockKey) throws InterruptedException {
CountDownLatch realLock = getRealLockByKey(lockKey);
// 为 null 说明此时锁已被删除, next race
if(realLock != null) {
realLock.await();
}
}
/**
* 二级锁解锁(如有必要)
*
* @param realLock 锁实例
*/
private static void releaseSecondLevelLock(CountDownLatch realLock) {
realLock.countDown();
}
/**
* 通过key 获取对应的锁实例
*
* @param lockKey 字符串锁
* @return 锁实例
*/
private static CountDownLatch getRealLockByKey(String lockKey) {
return lockKeyHolder.get(lockKey);
}
}
使用ConcurrentHashMap实现锁获取,性能还是不错的;
每个字符串对应一个锁,使用完成后就删除,不会导致内存溢出问题;
可以作为一个外部工具使用,业务代码接入方便,无需像 synchronized 一样,需要整段代码包裹起来;
本文只是想展示实现 String 锁,此锁并不适用于分布式场景下的并发处理;
/**
* 运行状态
*
* 4: 正在删除, 1: 正在放入队列中, 0: 正常无运行
*/
private transient volatile AtomicInteger runningStatus = new AtomicInteger();
// 更新时先获取该状态:
public void method5() {
AtomicInteger runningStatus = link.getRunningStatus();
// 正在删除数据过程中,则等待
if(!runningStatus.compareAndSet(, 1)) {
// 1. 等待另外线程删除完成
// 2. 删除正在更新标识
// 3. 重新运行本次数据放入逻辑
long lockStartTime = System.currentTimeMillis();
long maxLockTime = 10 * 1000;
while (!runningStatus.compareAndSet(, 1)) {
if(System.currentTimeMillis() - lockStartTime > maxLockTime) {
break;
}
}
runningStatus.compareAndSet(1, );
throw new RuntimeException("数据正在更新,重新运行: " + link.getLinkKey() + link);
}
try {
// do sync things
}
finally {
runningStatus.compareAndSet(1, );
}
}
public void method6() {
AtomicInteger runningStatus = link.getRunningStatus();
if (!runningStatus.compareAndSet(, 4)) {
logger.error(" 数据正在更新中,不得删除,返回 ");
return;
}
try {
// do sync things
}
catch (Exception e) {
logger.error("并发更新异常:", e);
}
finally {
runningStatus.compareAndSet(4, );
}
}
<END>
推荐阅读:
为啥国人偏爱 Mybatis,而老外喜欢 Hibernate/JPA 呢?

微信扫描二维码,关注我的公众号
朕已阅 
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69902700/viewspace-3160892/ ,如需转载,请注明出处,否则将追究法律责任。