我正在开发一个接受客户端的非常基本的服务器,并将数据从一个客户端写入连接的所有其他客户端。现在它工作正常,直到其中一个客户端断开连接,此时服务器下次尝试迭代客户端列表时,我从handle方法中得到了一个concurentmodification异常。我理解synchronized(clients)关键字的方式是,一旦一个线程调用了handle并开始迭代客户端列表,那么试图在该列表上调用add / remove的任何线程都会阻塞,直到句柄完成。
private void addClientThread(Socket _socket)
{
System.out.println("[DEBUG]: Adding client: "+_socket.getPort());
serverThread temp = new serverThread(this,_socket);
try
{
System.out.println("Server accepted new client: " + _socket+". Spawning new handler thread");
temp.open();
synchronized(clients)
{
clients.add(temp);
}
temp.start();
}
catch(IOException ioe)
{
System.out.println("Error opening thread: " + ioe);
}
}
public void remove(serverThread threadToRemove)
{
synchronized(clients)
{
clients.remove(threadToRemove);
}
try
{
threadToRemove.close();
System.out.println("Server closed client handler thread: "+threadToRemove.getId());
}
catch(IOException ex)
{
System.out.println("IO Exception while closing thread: "+ex);
}
}
public void handle(serverThread self,byte input)
{
synchronized(clients)
{
// Pass anything the client wrote to all of the other clients
for(serverThread temp : clients)
{
if(!temp.equals(self))
temp.send(input);
}
}
}