I have the main thread and ClientThread…
In the main thread when a user connects to the server it calls a method in the ClientThread
try {
Socket socket = server.accept();
clientThread.addClient(socket);
} catch(Exception e) {
e.printStackTrace();
}
the method in the ClientThread adds content to an ArrayList
public void addClient(Socket socket) {
clientSockets.add(socket);
}
The ClientThread also runs this code on every frame:
for (Socket socket : clientSockets) {
label.setText(socket.toString());
}
for some reason i get this erron java.util.ConcurrentModificationException on this line for (Socket socket : clientSockets) {…
The question: why do i get this error, and how can i fix that?
You need to synchronize access to
clientSockets, since you are not allowed to change the structure of aListwhile iterating over it.A simple solution would be to make
clientSocketsa synchronized collection, and then synchronize on it explicitly before iteration:You would need to do the same whereever you iterate over the list.
You can also consider using something like
CopyOnArrayList, which does not require you to synchronize, at the expense of using more memory and potentially serving slightly stale data.