Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A service stores active WebSocket sessions in a CopyOnWriteArrayList. With 50,000 sessions connecting and disconnecting constantly, CPU and allocation rate are very high. Explain and propose a replacement.

Every add or remove on a CopyOnWriteArrayList copies the whole backing array, so with 50,000 sessions each connect or disconnect copies 50,000 references, about 200 KB of garbage and O(n) work per change; remove(Object) also scans the list linearly to find the session first. With constant churn that becomes the dominant CPU and allocation cost. The replacement is ConcurrentHashMap.newKeySet() or a ConcurrentHashMap keyed by session id, which gives O(1) add and remove; broadcast iteration over it is weakly consistent, which is fine for sessions, and JFR should confirm the drop in allocation rate and GC after the change.

Why this question is asked

WebSocket servers keep a registry of open connections so they can broadcast messages, count users or close sessions on shutdown. CopyOnWriteArrayList often ends up holding that registry because the first version had 20 sessions and needed safe iteration while broadcasting. Then the product grows to 50,000 concurrent users, and the servers run hot without any obvious reason. Interviewers ask this scenario because it tests whether we can connect a data structure's cost model to a production symptom, and choose a replacement with the right guarantees. In this answer, we will recap how the list behaves on writes, calculate what the churn costs, replace it with a concurrent set or map, discuss the broadcast semantics, and verify with JFR.

1A Quick Recap of Copy-on-Write

CopyOnWriteArrayList keeps its elements in an array that is never modified once published. To add or remove, it takes a lock, makes a new array with the change, and swaps a volatile reference to point at it. Readers and iterators use whatever array they grabbed, without locks, which is why it is pleasant for broadcasting: we can loop over all sessions while others connect and disconnect, and nothing throws ConcurrentModificationException.

The design assumes writes are rare. With 50,000 sessions, users connecting and disconnecting all day, mobile clients reconnecting on every network change, writes are anything but rare.

2What the Churn Really Costs

Let us put numbers on it. Suppose 50,000 sessions are open and 500 sessions connect or disconnect each second, which is only 1 percent turnover per second for a large chat or notification service.

Java
List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
void onOpen(WebSocketSession s) { sessions.add(s); } // copies ~50,000 references
void onClose(WebSocketSession s) { sessions.remove(s); } // scans up to 50,000 elements, then copies
// per change: 50,000 refs x 4 bytes (compressed oops) = ~200 KB new array
// per second: 500 changes x 200 KB = ~100 MB/s of garbage, all under one write lock
Cost per connect or disconnect
OperationCopyOnWriteArrayListConcurrentHashMap key set
addCopy n refs, O(n), ~200 KBHash and insert, O(1), one node
removeScan O(n), then copy O(n)Hash and unlink, O(1)
Writers in parallelNo: one lock for all writesYes: lock per bin
Broadcast iterationSnapshot, lock-freeWeakly consistent, lock-free

Every change allocates a fresh 200 KB array, and the old one becomes garbage as soon as no iterator holds it. At 500 changes per second that is around 100 MB per second of allocation from this one list, which keeps the young generation collector busy constantly. Large arrays can even be allocated outside the normal young-generation path, for example as humongous objects in G1 when they exceed half a region, which makes them more expensive to reclaim.

remove(Object) adds a second cost: before copying, it must find the session, and the only way in an array is a linear scan calling equals on each element. On average that is 25,000 comparisons per disconnect. And because all writes share one lock, connects and disconnects are serialized; at peak reconnect storms, threads queue behind each other waiting to copy the same huge array.

3The Replacement: A Concurrent Set or Map

Sessions have no meaningful order and each one appears once, so what we really want is a set. ConcurrentHashMap.newKeySet() returns a thread-safe Set backed by a ConcurrentHashMap: add and remove hash the session to a bin and touch only that bin, in O(1) expected time, with no copying. If we also need to look sessions up by id, for example to send a message to one user, a ConcurrentHashMap<String, WebSocketSession> keyed by session id serves both needs.

Java
private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
void onOpen(WebSocketSession s) { sessions.put(s.getId(), s); } // O(1), no copy
void onClose(WebSocketSession s) { sessions.remove(s.getId()); } // O(1), no scan
void broadcast(TextMessage msg) {
for (WebSocketSession s : sessions.values()) { // lock-free, weakly consistent
if (s.isOpen()) {
send(s, msg); // see the note on slow clients below
}
}
}

Notice that we key by id rather than relying on the session object's equals and hashCode. Session ids are stable strings, so lookups and removals are predictable even if a framework wraps sessions in decorator objects.

4Is Weakly Consistent Iteration Good Enough?

With the list, a broadcast iterated a perfect snapshot. With ConcurrentHashMap, iteration is weakly consistent: it never throws, never shows an entry twice, and reflects the map at some point at or after the iterator was created, but sessions added or removed during the loop may or may not be visited. For sessions that is exactly right. A user who connected 2 milliseconds after the broadcast started may or may not receive it, which is indistinguishable from connecting 2 milliseconds later. A session closed during the loop is skipped by isOpen or fails its send harmlessly, which we must handle anyway because a client can disconnect at any moment.

There is one more design point the old list hid. Broadcasting by calling send on 50,000 sessions in one loop means one slow client can hold up everyone after it. Production servers usually give each session its own outbound buffer or use a decorator such as Spring's ConcurrentWebSocketSessionDecorator with a send time limit and buffer size, so the broadcast loop only enqueues.

5Verifying the Fix With JFR

We should prove the improvement, not assume it. Java Flight Recorder, the profiler built into the JDK, records allocation samples, GC pauses and CPU per method with low overhead. Recording the same load test before and after the change shows the difference directly.

Java
// start a 2-minute recording on the running service
// jcmd <pid> JFR.start duration=120s filename=/tmp/sessions.jfr settings=profile
// before: top allocation site CopyOnWriteArrayList.add / remove (~100 MB/s)
// after: top allocation site unrelated request handling; ConcurrentHashMap nodes are tiny

In JDK Mission Control we compare the allocation rate, the young GC frequency and the CPU share of the session registry. A healthy result is that the registry disappears from the top of the allocation and CPU profiles, and GC frequency drops in line with the removed garbage.

6Follow-up questions

Could we keep the list and just batch the changes?

Batching with addAll reduces copies, but disconnects arrive one at a time from many threads and must take effect promptly, so batching would need a queue and a background thread. That is more complexity than switching to a set, which simply has the right cost model for churn.

Why not Collections.synchronizedSet(new HashSet<>())?

Add and remove become O(1), but every broadcast has to hold the set's lock for the whole iteration, blocking all connects and disconnects while 50,000 sends happen. A concurrent key set gives O(1) changes and lock-free iteration together.

Do we lose memory by switching to ConcurrentHashMap?

Each entry costs a node object, roughly 32 bytes, so 50,000 sessions cost about 1.6 MB plus the table, versus 200 KB for one array. That is a trivial steady cost compared with allocating 100 MB per second of copied arrays.

7Conclusion

In this answer, we traced the high CPU and allocation to CopyOnWriteArrayList's cost model: each connect or disconnect copies the entire 50,000-element array, about 200 KB of garbage per change, and remove(Object) adds a linear scan, all under one write lock. We replaced it with a ConcurrentHashMap keyed by session id, or ConcurrentHashMap.newKeySet(), which makes add and remove O(1) with no copying, accepted weakly consistent iteration for broadcasts as a good fit for sessions, and used JFR to confirm the drop in allocation rate and GC.

What to say in the interviewAbout 100 seconds aloud

Open with

CopyOnWriteArrayList is built for lists that are read a lot and changed rarely, and this is the opposite. Every add or remove copies the whole backing array. With 50,000 sessions that's 50,000 references, roughly 200 KB with compressed pointers, for every single connect or disconnect.

Then, if they want more

At a few hundred changes a second that is on the order of 100 MB a second of garbage from this one list, plus the CPU to copy it, and all writes are serialized behind one lock. remove of an object is even worse because it first scans the array linearly calling equals to find the session, and only then copies.

So the cost is O(n) work and O(n) allocation per change, which explains both the CPU and the allocation rate. I'd replace it with a ConcurrentHashMap keyed by session id, or ConcurrentHashMap.newKeySet if I only need the set. Add and remove become O(1) and only lock one bin, and iteration for a broadcast is lock-free.

The difference is that iteration is weakly consistent rather than a snapshot, so a session that connects mid-broadcast might or might not get that message, which is fine for sessions, and closed sessions are handled by checking isOpen and handling send failures, which we need anyway. I'd also make sure a slow client can't block the broadcast loop.

Then I'd confirm the fix with a JFR recording under load, checking that the registry disappears from the allocation profile and GC frequency drops.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A service stores active WebSocket sessions in a CopyOnWriteArrayList. With 50,000...": https://scrivio-interview-library.netlify.app/java/concurrent-collections/496ba57f3b/