java - ConcurrentModificationException Issue When Running Two Thread -
so, working on server has support multie clients, have 1 thread checks if sockets have connected given port , adds them arraylist other thread uses update need client (update info, check datainputstream, send text on server) , on.
client code:
public class loop implements runnable{ arraylist<clientinstance> clientsconnected = new arraylist<clientinstance>(); @override public void run() { while(true) { checkinputstream(); } } public void checkinputstream() { (clientinstance s : clientsconnected) { s.checkinputstream(); } }
server code:
public synchronized void waitforclient() { try { system.out.println("waiting 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 clients connected! "); } catch (ioexception e) { e.printstacktrace(); } }
but when run server , connect 1 client it works fine, when connect 1 gives me issue:
exception in thread "thread-1" java.util.concurrentmodificationexception @ java.util.arraylist$itr.checkforcomodification(unknown source)
what do?
this because modifying arraylist (i.e. adding element in list in waitforclient()
method ) , @ same time iterating in checkinputstream()
method.
as mentioned @arjit use copyonwritearraylist
instead of arraylist
.
Comments
Post a Comment