Quick revision
The short answer
The bug is changing a player's score while the Player is inside the TreeSet: the tree placed the player by its old score, so after the change searches go the wrong way, remove fails, and re-adding creates a second copy. The correct update removes the player, changes the score, and re-inserts it, all under one lock if threads share the set. A sound design uses immutable entries, such as a record of (score, id), plus a HashMap from id to the current entry so we can find the old one; ConcurrentSkipListSet works for concurrent access with the same remove-then-add discipline, accepting that the two steps are not atomic together, and very large boards may belong in a sorted store such as a Redis sorted set.
What to remember
In this answer, we saw that changing a player's score while it sits in a TreeSet leaves its node at a stale position, so lookups and removal fail and a re-add creates a duplicate. The correct update removes the entry, changes the score and re-inserts it under one lock, and immutable (score, id) records with a HashMap from id to the current entry make that design hard to break. ConcurrentSkipListSet supports concurrent access with the same discipline but without atomicity across the two steps, and a Redis sorted set suits very large or shared boards.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The bug is changing a player's score while the Player is inside the TreeSet: the tree placed the player by its old score, so after the change searches go the wrong way, remove fails, and re-adding creates a second copy. The correct update removes the player, changes the score, and re-inserts it, all under one lock if threads share the set. A sound design uses immutable entries, such as a record of (score, id), plus a HashMap from id to the current entry so we can find the old one; ConcurrentSkipListSet works for concurrent access with the same remove-then-add discipline, accepting that the two steps are not atomic together, and very large boards may belong in a sorted store such as a Redis sorted set.
Why this question is asked
Leaderboards, priority queues and schedules all keep objects sorted by a value that changes. It is very tempting to keep mutable objects in a TreeSet and update them in place, and it works in a quick test. Then under real traffic, players appear twice, disappear from searches, or cannot be removed. Interviewers ask this scenario because it combines two ideas, how sorted collections locate elements and why their keys must not change, with concurrency and system design. In this answer, we will recap how TreeSet finds elements, reproduce the corruption, design the correct update, make it thread-safe, and decide when the leaderboard should move out of the JVM.
1A Quick Recap of How TreeSet Finds an Element
A TreeSet is a red-black tree ordered by its comparator, here score descending, then id. To find, remove or insert an element, it starts at the root and compares: if the element sorts before the node, it goes left; if after, right; if equal, it has found it. Each decision assumes that the elements already in the tree are still where their ordering says they should be.
The tree computes an element's position once, when it is inserted. It has no way to know that an element's fields changed later, so it does not move it. If the fields used by the comparator change, the element stays at a position that is now wrong, and every search that passes through that part of the tree may take a wrong turn.
2Reproducing the Corruption
Here is the mutable version, with a few players and one in-place update.
| Position in tree | Node | Comparator says it belongs |
|---|---|---|
| 1 | cat (90), new node | here, correct |
| 2 | ann (50) | here, correct |
| 3 | bob (40) | here, correct |
| 4 | cat (90), old node | at position 1, stranded |
Notice that every result is consistent with the tree's rules. The search for cat with score 90 starts at the root, which sorts below 90 in descending order, so it goes towards the high scores and never reaches cat's old node among the low scores. remove fails for the same reason, and add, finding no match on the new path, inserts a second node. Iteration then shows cat twice, and the old node may never be removable. Exactly the symptoms the users report.
3The Correct Update: Remove, Change, Re-insert
The rule for any sorted or hashed collection is that fields used for ordering or hashing must not change while the element is inside. So an update has three steps: remove the element while its fields still match its position, change the fields, and insert it again so the tree places it correctly. If several threads share the board, all three steps must run under one lock; otherwise a reader may miss the player between remove and add, or two updates may interleave.
- Acquire the board lock
- Look up the current entry by id
HashMap<String, Entry> - Remove the old entry from the TreeSetfields still match its position
- Create a new entry with the new score
- Add the new entry and update the map
- Release the lock
6 steps in order. Play them, or step through them one at a time.
4A Design With Immutable Entries
Rather than relying on discipline with a mutable Player, we make it impossible to change an entry in place. Each entry is an immutable record of score and id, and a HashMap from id to the current entry lets us find the old one without a search by value.
Notice that the id tie-breaker in the comparator also matters: without it, two players with the same score would compare as equal, and the TreeSet would silently drop one of them. Because entries are records with final fields, no code can corrupt the tree by mutating an entry. And because top returns a copy, callers never iterate the live set while another thread changes it.
5Concurrent Access With ConcurrentSkipListSet
A single lock is simple and is fine for many thousands of updates per second. If contention becomes a problem, ConcurrentSkipListSet offers the same NavigableSet operations with lock-free reads and concurrent writes, and a ConcurrentHashMap can replace the id map. We keep the same remove-then-add discipline, but must accept that the remove and the add are now two separate atomic operations, not one. For a brief moment the player is absent from the ranking, and a reader computing ranks may miss them; two concurrent updates of the same player could also interleave unless we serialise updates per id, for example with ConcurrentHashMap.compute on the id map wrapping both steps. For a game leaderboard, that brief gap is usually acceptable; for anything financial, it is not, and we would keep the lock.
6When the Board Outgrows the JVM
An in-memory TreeSet works for a single instance and a board of perhaps a few million players. When many service instances must share one board, or the board must survive restarts, a dedicated sorted store is a better fit. A Redis sorted set keeps members ordered by a score, updates with ZADD in O(log n), and answers rank and top-N queries with commands such as ZREVRANK and ZREVRANGE, atomically on the server. It solves the update problem by design, because the score is the sort key and changing it is a single operation that moves the member. The trade-offs are a network hop per operation and another system to operate.
7Follow-up questions
How would you return a player's rank efficiently?
TreeSet does not track subtree sizes, so headSet(entry).size() walks the elements and is O(n). For frequent rank queries, an order-statistic tree, a skip list with span counts, or a Redis sorted set with ZREVRANK, which is O(log n), is the right tool.
Why not simply re-sort a list of players on each read?
For small boards, that can be perfectly fine and avoids all of these problems. Sorting 10,000 players takes about a millisecond. It becomes a problem when reads are frequent and the board is large, which is when a structure that keeps the order incrementally pays off.
8Conclusion
In this answer, we saw that changing a player's score while it sits in a TreeSet leaves its node at a stale position, so lookups and removal fail and a re-add creates a duplicate. The correct update removes the entry, changes the score and re-inserts it under one lock, and immutable (score, id) records with a HashMap from id to the current entry make that design hard to break. ConcurrentSkipListSet supports concurrent access with the same discipline but without atomicity across the two steps, and a Redis sorted set suits very large or shared boards.
Open with
The problem is that scores are updated while players are inside the TreeSet. A TreeSet places an element by its comparator once, when it is inserted, and never re-sorts it.
Then, if they want more
When a score changes in place, the node stays at its old position, so a search for the new score goes down a different path and never finds it. remove fails, contains fails, and adding the player again inserts a second node at the new position, so the player appears twice and the old node can never be removed.
The fix is the rule for any sorted or hashed collection: fields used for ordering must not change while the element is inside. An update must remove the player, change the score and re-insert it, and if threads share the board, all three steps happen under one lock.
I would design it with immutable entries, a record of score and id, ordered by score descending and then id, so equal scores do not collapse, plus a HashMap from id to the current entry so I can find the old one to remove.
For more concurrency, ConcurrentSkipListSet and ConcurrentHashMap work with the same remove-then-add steps, accepting that the two steps are not atomic together. For very large or shared boards, I would use a Redis sorted set, where ZADD updates the score atomically and ZREVRANGE gives the top N.
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.
- Official documentation
- The Collections Framework, overview, java.util, package documentation
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 "You maintain a live leaderboard of players in a TreeSet<Player> ordered by score...": https://scrivio-interview-library.netlify.app/java/sets/3d6025a830/