项目背景
公司在做后台服务和netty通讯时,服务端发送消息到客服端 ,服务端需要阻塞,等待客户端响应后操作 ,之前采用的方案为synchronized + wait(使线程放弃CPU) + **notify(唤醒线程去竞争CPU)**的方案,发现会出现线程假死的情况,针对这一个情况进行优化
原流程
阻塞流程
Map<String, Object> attriMap = new HashMap<>();
attriMap.put("status", "0");
DeskDeviceSessionManager.addDeviceSessionAttribute(sessionid, attriMap);
sendResponsePacketByCommand(deskSession, deviceSendDTO.getDeviceNo(), deviceSendDTO.getCommand(), sessionid, deviceSendDTO.getData());
int count = 3;
//如果是截屏指令,则等待时间设置长一些
if (deviceSendDTO.getCommand().equals(DeviceCommandStrategyEnum.DEVICE_SCREENSHOT.getValue())) {
count = 10;
}
boolean isSucceed = false;
Object data = null;
while (count > 0){
synchronized (attriMap) {
try {
attriMap.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String status = (String)attriMap.get("status");
if (StringUtils.isNotEmpty(status)){
if ("1".equals(status)){
data = attriMap;
isSucceed = true;
DeskDeviceSessionManager.removeDeviceSessionAttribute(sessionid);
break;
}
}
count--;
}
}
唤醒流程
if (StringUtils.isNotEmpty(jsonData)){
String sessionId = requestPacket.getSessionid();
Map<String, Object> deviceSessionAttribute = DeskDeviceSessionManager.getDeviceSessionAttribute(sessionId);
synchronized (deviceSessionAttribute) {
Map<String, Object> dataMap = JsonMapper.nonEmptyMapper().fromJson(jsonData, Map.class);
Iterator<Map.Entry<String, Object>> iterator = dataMap.entrySet().iterator();
for (;iterator.hasNext();) {
Map.Entry<String, Object> next = iterator.next();
deviceSessionAttribute.put(next.getKey(), next.getValue());
log.info("key=" + next.getKey() + ",value=" + next.getValue());
}
deviceSessionAttribute.notify();
}
}
优化流程
采用semaphore实现阻塞
Map<String, Object> attriMap = new HashMap<>();
attriMap.put("status", "0");
DeskDeviceSessionManager.addDeviceSessionAttribute(sessionid, attriMap);
sendResponsePacketByCommand(deskSession, deviceSendDTO.getDeviceNo(), deviceSendDTO.getCommand(), sessionid, deviceSendDTO.getData());
Semaphore semaphore = new Semaphore(0);
DeskDeviceSessionManager.setDeskTcpSemaphoreSession(sessionid,semaphore);
boolean tryAcquire = semaphore.tryAcquire(5, TimeUnit.SECONDS);
boolean isSucceed = false;
Object data = null;
if (tryAcquire) {
isSucceed = true;
data = attriMap;
}else{
log.error("设备[" + deviceSendDTO.getDeviceNo() + "]会话[" + sessionid + "]未被唤醒,网络超时或其他异常,attriMap=" + attriMap.toString());
}
DeskDeviceSessionManager.removeDeviceSessionAttribute(sessionid);
唤醒流程
Map<String, Object> dataMap = JsonMapper.nonEmptyMapper().fromJson(jsonData, Map.class);
Iterator<Map.Entry<String, Object>> iterator = dataMap.entrySet().iterator();
for (;iterator.hasNext();) {
Map.Entry<String, Object> next = iterator.next();
deviceSessionAttribute.put(next.getKey(), next.getValue());
log.info("key=" + next.getKey() + ",value=" + next.getValue());
}
Semaphore semaphoreSession = DeskDeviceSessionManager.getDeskTcpSemaphoreSession(sessionId);
semaphoreSession.release();
其他方案
在阻塞代码块逻辑实现阻塞,然后启动一个线程进行消息监听 ,如果有消息,进行一个轮询通知,方案有多种,选择合适的即可