Remove from a collection during iteration
<p>I have set of <code>connection</code> objects (library code I cannot change) that have a <code>send</code> method.  If the sending fails, they call back a generic <code>onClosed</code> listener which I implement that calls <code>removeConnection()</code> in my code, which will remove the connection from the collection.</p>

<p>The <code>onClosed</code> callback is generic and can be called at any time.  It is called when the peer closes the connection, for example, and not just when a write fails.</p>

<p><em><strong>However</em></strong>, if I have some code that loops over my connections and sends, then the <code>onClosed</code> callback will attempt to modify a collection during iteration.</p>

<p>My current code creates a <em>copy</em> of the connections list before each iteration over it; however, in profiling this has shown to be very expensive.</p>

<pre><code>Set&lt;Connection&gt; connections = new ....;

public void addConnection(Connection conn) {
    connections.add(conn);
    conn.addClosedListener(this);
}

@Override void onClosed(Connection conn) {
    connections.remove(conn);
}

void send(Message msg) {
    // how to make this so that the onClosed callback can be safely invoked, and efficient?
    for(Connection conn: connections)
        conn.send(msg);
}
</code></pre>

<p>How can I efficiently cope with modifying collections during iteration?</p>
