WEBSOCKET報錯:The remote endpoint was in state [TEXT_FULL_WRITING]

報錯:The remote endpoint was in state [TEXT_FULL_WRITING] which is an invalid state for called method 

public void sendMessage(String message) {
        ThreadPoolExecutor cachedThreadPool = ThreadPoolUtil.getCachedThreadPool();
        cachedThreadPool.execute(
          session.getAsyncRemote().sendText(message)
        );
    }

併發衝突,修改後

public void sendMessage(String message) {
        ThreadPoolExecutor cachedThreadPool = ThreadPoolUtil.getCachedThreadPool();
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    synchronized (session){
                        session.getBasicRemote().sendText(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

使用synchronized 對資源加鎖,同時使用線程池優化資源的開銷

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章