i have a HashMap of ClientSocket and Client Object.
i'm iterating throw them using for loop, but sometimes new lines are added to the hashmap and then i get the java.util.ConcurrentModificationException error. i accutally understand why it happens, but i don't understand how to solve it. i've tried to make a new copy of my HashMap before the iteration starts but yet - i still got the error.
my code:
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 is the function that because of it i'm getting the error.
removeClientSocket