Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

A pricing engine keeps hot data in large primitive arrays for speed, and new team members keep introducing bugs with index arithmetic. How do you keep the performance while making the code safer?

We keep the primitive arrays but stop letting most of the code touch them directly. The arrays go inside small classes with intention-revealing methods, such as priceAt(instrument, day), that check their inputs at the API boundary with Objects.checkIndex while the hot inner loops stay internal. Ad hoc index code is replaced with JDK helpers such as Arrays.mismatch and the range versions of Arrays.equals, the invariants are written down, and property-based tests plus JMH benchmarks guard correctness and speed. MemorySegment, and the still-incubating Vector API, are options for off-heap or SIMD-heavy parts where they fit.

Why this question is asked

Performance-critical systems often trade readability for speed early, and the trade compounds: after a few years, a pricing engine's core is a set of double[] arrays indexed with expressions like base + inst * days + d - 1 scattered across hundreds of methods. Each new team member is one wrong offset away from mispricing a product, and the bug is silent. Interviewers ask this design question to see whether we can make such code safer without throwing away the performance that justified it. In this answer, we will recap why raw index code is risky, wrap the arrays behind safe APIs, use JDK helpers for bounds and ranges, write down invariants, add tests and benchmarks, and look at off-heap and SIMD options.

1A Quick Recap: Why Raw Index Arithmetic Breaks

Suppose prices for 2,000 instruments over 260 trading days are stored in one flat double[] of 520,000 entries, in row-major order: the price of instrument i on day d is at index i * 260 + d. This is fast, because the data is contiguous and loops run without pointers or boxing.

The danger is that Java only checks that an index is inside the whole array, not that it is the index we meant. If someone writes d * 260 + i instead, or uses 1-based days in one method and 0-based days in another, the code reads a valid slot holding another instrument's price. No exception is thrown; the result is just wrong. So the bugs we are fighting are not crashes but silent wrong answers, which is far worse for a pricing engine.

2Wrapping the Arrays Behind Intention-Revealing Methods

The first step is to give each array an owner: a small final class that holds the array privately and offers methods named after what callers mean. Validation happens once at that boundary, and the index arithmetic exists in exactly one place.

Java
public final class PriceGrid {
private final int instruments, days;
private final double[] prices; // row-major: [instrument][day]
public PriceGrid(int instruments, int days) {
this.instruments = instruments;
this.days = days;
this.prices = new double[Math.multiplyExact(instruments, days)];
}
public double priceAt(int instrument, int day) {
return prices[index(instrument, day)];
}
public void setPrice(int instrument, int day, double price) {
prices[index(instrument, day)] = price;
}
private int index(int instrument, int day) {
Objects.checkIndex(instrument, instruments); // fails with a clear message
Objects.checkIndex(day, days);
return instrument * days + day;
}
}
PriceGrid g = new PriceGrid(2000, 260);
g.priceAt(5, 300); // IndexOutOfBoundsException: Index 300 out of bounds for length 260

Notice what the checks buy us. Without them, priceAt(5, 300) would quietly read instrument 6's price on day 40, because 5 * 260 + 300 is a valid index. With them, the mistake fails immediately with a message that names the wrong value. Objects.checkIndex, added in Java 9, is treated specially by the JIT, which handles it like its own array bounds checks and can often remove it when it proves the index is in range, so the safety is cheap.

3Keeping the Hot Loops Fast

Calling priceAt for every element inside the innermost loop of a risk calculation would add two checks per element. So the class also offers bulk operations that run the tight loop internally, over raw indexes the class itself computed, with the checks done once for the whole range.

Java
/** Average price of one instrument over days [from, to). */
public double averagePrice(int instrument, int from, int to) {
Objects.checkIndex(instrument, instruments);
Objects.checkFromToIndex(from, to, days); // checked once for the whole range
int base = instrument * days;
double sum = 0;
for (int i = base + from; i < base + to; i++) sum += prices[i]; // tight loop, no per-element checks of ours
return sum / (to - from);
}
Step throughWhere index arithmetic lives after the change
  1. Pricing and risk codecalls priceAt, averagePrice, shiftScenario
  2. PriceGrid APIchecks indexes once with checkIndex and checkFromToIndex
  3. Internal bulk loopsraw index arithmetic, written and reviewed once
  4. double[] pricesone flat array, row-major

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

Callers express what they want, an average over a range, and the class keeps the speed of a raw loop. Over time, the set of bulk operations grows with the engine's real needs: moving averages, scenario shifts, copying a row. Each is written and reviewed once by the people who own the class. The JIT inlines small final methods like these, so the abstraction costs essentially nothing at run time; we confirm that with benchmarks rather than assuming it.

4Replacing Ad Hoc Index Code With JDK Helpers

A lot of fragile index code reimplements things the JDK already has. Comparing two slices of arrays, finding where two price curves start to differ, or checking a range is valid all have tested, optimised methods.

Java
double[] today = ..., yesterday = ...;
int first = Arrays.mismatch(today, yesterday); // -1 if equal, else first differing index
boolean same = Arrays.equals(today, 0, 260, yesterday, 0, 260); // compare one instrument's row (Java 9+)
Objects.checkFromIndexSize(offset, length, prices.length); // validate an (offset, length) pair

Arrays.mismatch and the range overloads of Arrays.equals and Arrays.compare are vectorised inside the JDK, so they are usually faster than a hand loop and they get boundary handling right. Objects.checkFromToIndex and checkFromIndexSize replace the hand-written if statements that are so easy to get wrong by one.

5Writing Down the Invariants

Many index bugs come from assumptions nobody wrote down. Is the day dimension 0-based or 1-based? Are the curve points sorted by tenor? Does NaN mean a missing price, or is there a sentinel such as -1? We document each invariant in the class's Javadoc, and where we can, we check it: the constructor of a sorted curve verifies the order once, and a missing price is represented by Double.NaN consistently, never by a magic number that could be mistaken for a real price. A short design note explaining the layout, with a diagram of the row-major order, is often the most useful onboarding document the team has.

6Guarding Correctness and Speed With Tests

Two kinds of tests protect the change. Property-based tests, with a library such as jqwik, generate thousands of random grids and indexes and check rules that must always hold: setPrice followed by priceAt returns the same value, averagePrice over one day equals priceAt, and an out-of-range index always throws. These catch the off-by-one cases nobody thought to write by hand.

JMH benchmarks protect the speed. We benchmark the main kernels, for example a full revaluation over all instruments and days, before and after the refactoring, and keep the benchmarks in the build so a later change that adds a per-element check in a hot loop shows up as a regression, not as a surprise in production.

7Off-Heap Data and SIMD Where They Fit

For data too large for the heap or shared with native code, java.lang.foreign.MemorySegment, final since Java 22, gives bounds-checked access to off-heap memory with explicit lifetimes, which is far safer than the older Unsafe tricks. For kernels that C2 does not vectorise well, the Vector API can express SIMD operations directly, but in Java 25 it is still an incubator module (check your version), so we would use it only inside a contained kernel behind the same PriceGrid API, where it can be replaced without touching callers.

8Follow-up questions

Do the extra checks slow down the engine?

Usually not measurably, because checks happen at the API boundary or once per range, and the JIT removes checks it can prove redundant. The benchmarks are there to confirm it. If a specific hot path does slow down, we add a bulk method for it rather than removing the checks everywhere.

Why not just switch to a matrix library?

That can be a good option, but it is a bigger change and adds a dependency. Wrapping the existing arrays keeps the proven performance and fixes the safety problem in small steps, and a later move to a library would happen behind the same API.

How do you stop people from bypassing the wrapper?

The array field is private and never returned, so code outside the class cannot index it. A build rule, for example with ArchUnit, can also forbid new public methods that return or accept raw double[] in the pricing packages.

9Conclusion

In this answer, we kept the pricing engine's primitive arrays but made them safe to use. Each array lives in a small class with intention-revealing methods that check indexes at the boundary with Objects.checkIndex, while bulk operations keep the raw loops internal and fast. JDK helpers such as Arrays.mismatch, ranged Arrays.equals and the Objects range checks replace hand-written index code, invariants are documented, property-based tests and JMH benchmarks guard correctness and speed, and MemorySegment or the incubating Vector API remain options behind the same API where they fit.

What to say in the interviewAbout 90 seconds aloud

Open with

I'd keep the primitive arrays, because they are why the engine is fast, but I would stop letting most of the code do index arithmetic. Each array gets an owner: a small final class like PriceGrid that keeps the array private and offers methods named for what callers mean, such as priceAt(instrument, day).

Then, if they want more

The index formula lives in one private method, and inputs are checked with Objects.checkIndex, which the JIT treats like its own bounds checks, so it's cheap. That matters because the real danger isn't an exception, it's a wrong index that is still inside the array and silently reads another instrument's price.

For hot paths, the class offers bulk operations, like an average over a range, that check the range once with checkFromToIndex and then run the raw loop inside, so we keep the speed.

I'd replace hand-written comparisons and range checks with Arrays.mismatch, the ranged Arrays.equals, and the Objects range helpers, and write down invariants like zero-based days and NaN for missing prices. Then I'd add property-based tests for things like set then get, and keep JMH benchmarks in the build so we notice if safety costs speed.

For very large or native-shared data I'd consider MemorySegment, and maybe the Vector API for a specific kernel, though it's still incubating in Java 25.

About this answer

Last updated
12 November 2026
Versions it names
Java 9, Java 22, Java 25
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 pricing engine keeps hot data in large primitive arrays for speed, and new team...": https://scrivio-interview-library.netlify.app/java/arrays/4a10813752/