我正在寫一個服務器到客戶端之間交換消息。還有一個問題需要解決,即如何在客戶關閉時發佈頻道。我所做的就是啓動監視器線程,其中監視所有客戶端映射,並且如果在嘗試寫入()時檢測到異常,我會嘗試刪除()通道。但是,在關閉客戶端之後,monitor線程中的write()方法不會拋出異常,所以無用的通道永遠不會被釋放。任何人都知道爲什麼?SocketChannel的write()方法不拋出一個異常時,它應該做的
public class ServerMonitor extends Thread{
private Map<String, SocketChannel> allClients;
private Set set;
private Iterator it;
private Entry entry;
private SocketChannel channel;
private ByteBuffer buf;
public ServerMonitor(Map<String, SocketChannel> allClients) {
this.allClients = allClients;
buf = ByteBuffer.allocateDirect(10);
byte b = 0;
buf.put(b);
buf.flip();
}
public void run(){
while(true) {
if(!allClients.isEmpty()) {
set = allClients.entrySet();
it = set.iterator();
while(it.hasNext()) {
entry = (Entry) it.next();
channel = (SocketChannel) entry.getValue();
try{
channel.write(buf);
} catch(Exception e) {
allClients.remove(entry.getKey());
//set.remove(entry);
}
}
}
try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
'this.allClients = allClients;'< - 這是相當危險的,除非你真的知道自己在做什麼......如果主叫方修改了地圖,你的類地圖將看到的變化! 'ConcurrentModificationException'的好源... – fge
@fge我想執行this.allClients = allClients;因爲當監視器線程檢測到無法寫入字節的通道時,我需要修改源allClients(釋放一個無用的通道)。 – dastan