Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentModificationException Issue When Running Two Thread

So, I am currently working on a server that has support for multie clients, I have one thread that checks if any sockets have connected to the given port and then adds them to an arraylist that the other thread uses to update everything I need to do with the client (Update Info, Check The DataInputStream, Send Text over server) and so on.

Client Code:

public class Loop implements Runnable{

ArrayList<ClientInstance> clientsConnected = new ArrayList<ClientInstance>();

@Override
public void run() {
    while(true) {
        checkInputStream();
    }

}

public void checkInputStream() {
    for (ClientInstance s : clientsConnected) {
        s.checkInputStream();
    }
}

Server Code:

public synchronized void waitForClient() {
    try {
        System.out.println("Waiting for client on port: "
                + serverSocket.getLocalPort());
        Socket client = serverSocket.accept();
        System.out.println("Client Connected! " + client.getInetAddress());
        loop.getClientsConnected().add(new ClientInstance(client));
        System.out.println("Client added to clients connected! ");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

But when I run the server and then connect one client to it it works fine, but when i connect another one it gives me this issue:

Exception in thread "Thread-1" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)

What do I do?

like image 398
Grobbed Avatar asked Jul 31 '26 14:07

Grobbed


1 Answers

This is because you are modifying arraylist (i.e. adding element in list in waitForClient() method ) and at the same time you are iterating it in checkInputStream() method.

As mentioned by @Arjit use CopyOnWriteArrayList instead of ArrayList.

like image 159
Naman Gala Avatar answered Aug 02 '26 05:08

Naman Gala