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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With