使用Semaphore优化线程假死方案

项目背景

公司在做后台服务和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();

其他方案

在阻塞代码块逻辑实现阻塞,然后启动一个线程进行消息监听 ,如果有消息,进行一个轮询通知,方案有多种,选择合适的即可

Semaphore(信号量)是Java中的一个同步控制工具类,它可以用来控制对共享资源的访问数量。在单线程并发的场景中,Semaphore通常用于控制资源的并发访问次数,以确保不会超出资源的处理能力。 在单线程并发的使用中,通常只有一个线程会访问受保护的资源,但可能会有多个并发的请求需要处理。通过 Semaphore,我们可以限制同时进行的处理数量,使得线程以一定的速率处理请求,而不是让线程在资源不可用时就直接阻塞,从而提高系统的吞吐量和资源的利用率。 以下是如何在单线程并发的场景中使用Semaphore的一个例子: 1. 创建一个Semaphore实例,并指定并发访问的最大数量。 2. 在请求处理逻辑中,调用`acquire()`方法获取信号量,如果信号量已经被其他请求占用,则当前线程将阻塞等待,直到有信号量可用。 3. 处理完请求后,调用`release()`方法释放信号量,使得其他线程可以继续获取信号量执行请求。 示例代码如下: ```java import java.util.concurrent.Semaphore; public class SingleThreadedConcurrency { private Semaphore semaphore; public SingleThreadedConcurrency(int permits) { semaphore = new Semaphore(permits); // 创建一个信号量,最大并发数为permits } public void processRequest() { try { semaphore.acquire(); // 尝试获取信号量,如果没有可用的信号量,则线程将阻塞 // 处理请求的代码逻辑... } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { semaphore.release(); // 释放信号量,允许其他线程进入 } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值