i have this loop:

```
for (Iterator<Socket> it = collection.iterator(); it.hasNext();) {
    Object obj = it.next();
    new Thread( () -> {
        if(myCondition(obj)){
            it.remove();
        }
    }).start();
}

```

Sometimes it works, but sometimes i get a `java.lang.IllegalStateException` when calling `it.remove();`
Is there a safe way to do this?

**---UPDATE---**

I need to do this in a code running on a Server, that receives connections from a lot of client Sockets. This code performs some queries from time to time, and for each time a query is performed, the result is sent to all the connected sockets. So, for each socket, i create a new Thread to do this. What i am trying to remove from the list are the closed sockets.

This is a sample of how my server works:

```
public class SocketServidor {
    static ServerSocket serverSocket;
    static List<Socket> socketsConectados = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        serverSocket = new ServerSocket(5963);

        new Thread( ()-> {
            lacoConexao:
            while(true) {
                try {
                    socketsConectados.add(serverSocket.accept());
                } catch (IOException ex) {
                    Logger.getLogger(SocketServidor.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }).start();

        lacoMensagens:
        while(true) {
            int valor = (int) (Math.random() * 3) + 1;
            lacoIterators:
            for (Iterator<Socket> it = socketsConectados.iterator(); it.hasNext();) {
                Socket socket = it.next();
                new Thread( () -> {
                    try {
                        if(socket.isClosed()) {
                            return;
                        }
                        PrintWriter out = new PrintWriter(socket.getOutputStream());
                        out.println("Você acabou de ganhar R$ "+new DecimalFormat("###,##0.00").format(valor)+" às "+new SimpleDateFormat("HH:mm:ss").format(new Date())+"!");
                        if(out.checkError()){
                            socket.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }).start();
            }
            System.out.println("Sockets conectados: "+socketsConectados.size());
            Thread.sleep(valor*1000);
        }
    }
}

```