0

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?

0

2 Answers 2

4

You need to synchronize access to clientSockets, since you are not allowed to change the structure of a List while iterating over it.

A simple solution would be to make clientSockets a synchronized collection, and then synchronize on it explicitly before iteration:

List<Socket> clientSockets = Collections.synchronizedList(new ArrayList<Socket>());


//...when setting the labels:
synchronized (clientSockets) {
    for ( Socket socket : clientSockets ) {
        label.setText(socket.toString());
    }
}

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.

Sign up to request clarification or add additional context in comments.

2 Comments

synchronize(clientSockets) { is that a method?
@Chorche: No, it's a language keyword but I had a typo. Should be synchronized.
0

Javadoc says " If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.".

Just setting label is not structural modification, so i am not sure if that is the cause of exception.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.