Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

You need an in-memory structure of price updates keyed by timestamp that supports range queries (all updates between two times) and is read and written by many threads. Which Java collection would you choose and why?

ConcurrentSkipListMap is the natural choice: it keeps keys sorted, offers subMap, headMap and tailMap range views, and lets many threads read and write without a global lock. TreeMap behind a lock is simpler but serialises every access, while skip lists cost more memory and have worse locality than arrays. If updates arrive in time order and old data expires, time-bucketed arrays or a ring buffer can be faster and smaller, so the decision rests on the read/write ratio, range sizes and retention.

Why this question is asked

Design questions about collections are really questions about trade-offs. Several structures can answer "give me all updates between two times", and the interviewer wants to hear how we compare them under concurrency, memory and access patterns rather than a single class name. In this answer, we will set out what the structure must do, see how ConcurrentSkipListMap meets it, look at the simpler and the faster alternatives, and finish with how to decide between them.

1What the Structure Must Do

We have three requirements. First, range queries: all price updates between time t1 and time t2, which needs the data ordered by timestamp. Second, concurrency: many threads write updates and many threads read ranges at the same time. Third, it lives in memory, so its size and its effect on the garbage collector matter.

A HashMap fails the first requirement immediately, because it has no order. So we are choosing between sorted structures, and the question is how each one handles concurrent access and memory.

2How ConcurrentSkipListMap Works

A skip list is a sorted linked list with extra express lanes. The bottom level links every entry in key order. Above it, index levels link a random subset of entries, each level skipping more of them. To find a key, we start at the top level, move right while the next key is smaller, drop down a level, and repeat. On average that takes logarithmic time, like a balanced tree.

ConcurrentSkipListMap implements this with compare-and-swap operations instead of locks. Inserting links in a new node with an atomic update, and readers never block. That makes it a sorted, thread-safe NavigableMap without a global lock, and its range views are exactly the query we need.

Java
ConcurrentNavigableMap<Long, PriceUpdate> updates = new ConcurrentSkipListMap<>();
// writers, from many threads
updates.put(update.timestampNanos(), update);
// readers: all updates in [from, to)
ConcurrentNavigableMap<Long, PriceUpdate> window =
updates.subMap(from, true, to, false); // a live view, no copy
for (PriceUpdate u : window.values()) { ... } // iterates in time order
updates.headMap(cutoff).clear(); // drop everything older than cutoff
Step throughSkip list levels for timestamp keys
  1. Level 2 index10:00:00 -> 10:00:40
  2. Level 1 index10:00:00 -> 10:00:20 -> 10:00:40 -> 10:01:00
  3. Base levelevery update in timestamp order, linked one after another

3 layers, from the top down. Step through them one at a time.

A search starts at the top and drops down a level each time the next key is too large.

Notice two details. The range view is weakly consistent: iterating it never throws ConcurrentModificationException, but it may or may not show updates inserted while we iterate. And there is a modelling catch: two updates with the same timestamp would overwrite each other. In real price feeds that happens, so the key should be unique, for example a record of timestamp and sequence number, or the value should hold a small list of updates for that instant.

3The Simpler Option: TreeMap With a Lock

TreeMap is a red-black tree with the same NavigableMap API, but it is not thread-safe. We can wrap it with a ReentrantReadWriteLock or Collections.synchronizedNavigableMap. This is simple and uses a little less memory per entry than a skip list.

The cost is that all access is serialised. With a plain lock, one reader scanning a large range blocks every writer for the duration of the scan. A read-write lock lets readers proceed together, but writers still wait for all readers to finish. With many threads writing price updates, that lock becomes the bottleneck, which is exactly the problem ConcurrentSkipListMap avoids.

4The Cost of a Skip List

A skip list is not free. Each entry is a node object holding the key, the value and a next reference, and roughly one entry in four also carries one or more index objects for the express lanes. With a boxed Long key and the update object itself, that is several small objects per update, scattered around the heap. Scanning a range follows references from node to node, touching a new cache line for most entries, which is much slower than reading a contiguous array.

So for a few hundred thousand updates this is entirely fine. For hundreds of millions, or for code that scans large ranges constantly, the memory and the pointer chasing start to dominate.

5The Faster Option: Time-Bucketed Arrays

Price updates usually arrive roughly in time order, and old updates are usually discarded after some retention period. Those two facts allow a much more compact design. We divide time into buckets, for example one per second, and keep a ring buffer of buckets covering the retention window, such as 3,600 buckets for one hour. Each bucket stores its updates in arrival order in arrays, ideally primitive arrays of timestamps and prices.

A range query computes the first and last bucket from the timestamps, scans the buckets in between sequentially, and trims the edges with a binary search. Expiry is free: when the ring wraps around, the oldest bucket is simply reused. If each instrument has a single writer thread, writes need no locks at all, and readers can use a published counter to see how much of a bucket is complete.

Choosing the structure
StructureConcurrencyMemory and localityBest when
ConcurrentSkipListMaplock-free reads and writesseveral objects per entry, pointer chasinggeneral case, moderate size
TreeMap + lockserialised, readers can block writersa bit less per entrylow write rate, simplicity first
Time-bucketed ring buffersingle writer per bucket, cheap readscompact arrays, sequential scanstime-ordered arrival, fixed retention

6Making the Decision

We decide from the workload, so the first step is to ask for numbers. How many updates per second, and from how many threads? How many range queries per second, and how wide are they, the last second or the last day? How long must data be kept, and can updates arrive out of order?

If the rates are moderate and updates can arrive out of order, ConcurrentSkipListMap with a unique composite key is the right default: correct, concurrent and simple to reason about. If write rates are low and the team values simplicity, a TreeMap with a read-write lock is acceptable. If the feed is high-volume, time-ordered and retained for a fixed window, the bucketed ring buffer wins on memory, GC pressure and scan speed, at the cost of custom code that we must test carefully.

7Follow-up questions

Why not use a ConcurrentHashMap and sort on read?

Sorting on every range query costs O(n log n) for the whole data set, while a sorted structure answers in O(log n) plus the size of the range. It only makes sense if range queries are very rare compared with writes.

Is size() on ConcurrentSkipListMap cheap?

No. It walks the whole base level and is not exact while updates are happening. If we need a count, we should keep a separate counter such as a LongAdder.

How would you handle updates that arrive slightly out of order in the bucketed design?

Insert each update into the bucket its timestamp belongs to, and allow buckets to remain writable for a short grace period. Within a bucket, either keep the arrays sorted on insert, which is cheap when disorder is small, or sort a bucket once it closes.

8Conclusion

In this answer, we saw that range queries rule out hash maps and leave sorted structures. ConcurrentSkipListMap gives sorted, lock-free access with subMap, headMap and tailMap range views, provided we make keys unique, while TreeMap with a lock is simpler but serialises access. Skip lists pay with memory and pointer chasing, so for a time-ordered feed with fixed retention, time-bucketed arrays in a ring buffer are smaller and faster. The choice follows from the read/write ratio, range sizes and retention.

What to say in the interviewAbout 90 seconds aloud

Open with

My default would be ConcurrentSkipListMap keyed by timestamp. It keeps keys sorted, so I can use subMap, headMap and tailMap to get exactly the updates between two times as a live view, and it is built on compare-and-swap rather than a global lock, so many threads can write and read at the same time without blocking each other.

Then, if they want more

Iteration is weakly consistent, which is fine for this kind of query. One thing I would fix in the model: two updates can share a timestamp, so I would use a unique key such as timestamp plus sequence number. The alternative is a TreeMap guarded by a read-write lock.

It is simpler, but all writers wait while a reader scans a large range, so with many writers it becomes the bottleneck. The cost of the skip list is memory and locality: several small objects per update and pointer chasing during scans. So I would ask about volumes.

If updates arrive in time order and old data expires, say we keep one hour, I would consider time buckets in a ring buffer, with primitive arrays per bucket and ideally a single writer per instrument, which makes scans sequential and expiry free. The decision depends on the read/write ratio, how wide the ranges are, and the retention period.

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 "You need an in-memory structure of price updates keyed by timestamp that supports range...": https://scrivio-interview-library.netlify.app/java/java-performance/e299bccb63/