我有一个 ClientSocket 和客户端对象的 HashMap。
我正在使用 for 循环迭代抛出它们,但有时会在哈希图中添加新行,然后我得到 java.util.ConcurrentModificationException 错误。我完全理解它为什么会发生,但我不明白如何解决它。我试图在迭代开始之前制作我的 HashMap 的新副本,但是 - 我仍然得到错误。
我的代码:
private volatile HashMap<ClientSocket, Client> clientsMap = new HashMap<ClientSocket, Client>();
private volatile HashMap<ClientSocket, Client> iteratorClientsMap = new HashMap<ClientSocket, Client>();
private volatile ClientsMapIterator iterator;
iterator = new ClientsMapIterator(clientsMap);
iteratorClientsMap = iterator.getItreator();
for (Map.Entry<ClientSocket, Client> entry : iteratorClientsMap.entrySet()) {
ClientSocket key = entry.getKey();
//Client value = entry.getValue();
long diff = currentTime - key.getLastOnline();
boolean isAvailable = false;
try {
isAvailable = (key.getSocket().getInputStream().available() > 0);
} catch (IOException e) {
e.printStackTrace();
}
if ( diff > keepAlive)
removeClientSocket(key);
}
public synchronized void addClientSocket(ClientSocket clientSocket) {
clientsMap.put(clientSocket, null);
}
addClientSocket 是因为它我得到错误的函数。