3 Replies Latest reply: Aug 12, 2009 3:41 PM by 796440 RSS

    Concurrent Modification Exception from synchronized block

      I have a problem trying to identify how a concurrent modification exception is being thrown.

      Basically I have a list of Client objects. This list holds the currently connected clients. When a user starts using the server their client object gets added to this array list. When they exit, their client thread calls a disconnect method which simply removes their entry from the arraylist.

      I've synchronized both these parts yet it seems it's still throwing the same exception. For some reason I doubt there is even a concurrent modification going on because regardless whether someone is connecting at the same time as someone disconnects it still throws the exception.

      Anyway, here's the code:

      This part is called by the client thread when the client thread generates an IOException - usually someone quitting.
          public synchronized void disconnectClient(Client theClient)
              for(Object aClient : connectedClients)
                  if(theClient == (Client)aClient)
      This part is the server thread:
                  while (true)
                      // Wait for client connection
                      clientUpdateSocket = serverUpdateSocket.accept();
                      clientBroadcastSocket = serverBroadcastSocket.accept();
                      System.out.println("I've detected an incoming connection originating from: " + clientUpdateSocket.toString());
                      // Create the new client
                      Client newClient = new Client(clientUpdateSocket, clientBroadcastSocket, dbConnection, this);
                      // Add it to list of clients to be monitored
                      synchronized (this)
                      // Send the client off to a new thread to deal with itself
                      new Thread(newClient).start();
      I would of thought the synchronized blocks would deal with this but it seems it's not the case. Help is very much appreciated!