基于静态变量的缓存锁

//LineStationProcessor类
//静态资源(想保证集合类的线程安全可以使用--ConcurrentHashMap<基于分段锁,效率要高于HashTable>)
public static Map<String,DhMdispatchcommandDTO> dispatchType = new HashMap<>();
//business_request_code 和 lastType.getRequestcode() 锁的资源类型
String business_request_code = bri.getBusiness_request_code();
//获取缓存是否含有当前车辆指令
DhMdispatchcommandDTO lastType = LineStationProcessor.dispatchType.get(device_id);
//过期时间
long expirationTime = 0;
long nowTime = System.currentTimeMillis();
if(lastType != null){
	expirationTime = lastType.getTimemsec();
	lastType.setTimemsec(nowTime + 5000);
	LineStationProcessor.dispatchType.put(device_id, lastType);
}
// 判断两种类型是否相同,不同即sleep5秒
if (lastType != null && !business_request_code.equals(lastType.getRequestcode()) && nowTime < expirationTime) {
	long isNowTime = 0;
	while (true) {
		try {
		    //500毫秒判断一次
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		isNowTime = System.currentTimeMillis();
		if (isNowTime > expirationTime) {
			break;
		}
	}
	isNowTime += 5000;
	nowTime = isNowTime;
}else{
    //避免为null,所以重新new一个
	lastType = new DhMdispatchcommandDTO();
	nowTime += 5000;
}
//缓存中没有记录或是睡眠完成后在之前的时间加超时,未睡眠加5秒,睡眠需加10秒,实际 超时时间均为5秒
lastType.setRequestcode(business_request_code);
lastType.setTimemsec(nowTime);
LineStationProcessor.dispatchType.put(device_id, lastType);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值