Scrivio Interview library
ScenarioAdvanced8 min read · updated 12 November 2026

A Java pricing service multiplies 2,000 x 2,000 double matrices for each risk calculation using double[][] and a naive i-j-k triple loop. It is too slow and the team proposes rewriting in C++. What would you try first in Java, and how do you decide?

Before any rewrite, I would fix the memory access pattern: changing the loop order from i-j-k to i-k-j makes the inner loop walk rows sequentially instead of jumping down a column, which is often several times faster and lets the JIT vectorize it. Next I would store each matrix in a flat row-major double[], add blocking (tiling) so the working set fits in cache, and only then parallelize across rows with a ForkJoinPool or parallel streams, measuring each step with JMH. The Vector API, still incubating in Java 25, and mature libraries such as EJML or native BLAS called through the Foreign Function and Memory API can give large further gains. I would decide on measured results against the latency target, weighing the C++ option's extra language, build and native boundary costs.

Why this question is asked

A 2,000 x 2,000 matrix multiplication is 8 billion multiply-adds, and a naive loop can take tens of seconds, which is a disaster for a pricing service that must answer quickly. Teams in this situation often conclude that Java is too slow. Usually the code is slow because of how it touches memory, and the same problem would exist in C++. Interviewers ask this to see whether a senior engineer measures and fixes the cause before proposing a costly rewrite. In this answer, we will recap why memory access dominates, fix the loop order, flatten and block the data, parallelize, look at the Vector API and libraries, and then decide with numbers.

1A Quick Recap: Why Memory Access Dominates

Multiplying two n x n matrices A and B gives C, where each C[i][j] is the sum over k of A[i][k] x B[k][j]. For n = 2,000 that is 2,000^3 = 8 x 10^9 multiply-adds. A modern core can do several billion floating-point operations per second, so in theory this takes a few seconds on one core, and much less with SIMD instructions, which process 4 or 8 doubles in one instruction.

In practice, the naive loop is far slower because of memory. Each matrix is 2,000 x 2,000 x 8 bytes, 32 MB, much larger than the CPU caches, which range from tens of kilobytes (L1) to a few tens of megabytes (L3). The CPU reads memory in 64-byte cache lines, eight doubles at a time, and runs fast only when it uses all eight values of each line it loads.

2Change the Loop Order

In the naive i-j-k order, the inner loop runs over k and reads B[k][j], one element from each row of B. In Java, double[][] is an array of separate row arrays, so every step jumps to a different array in memory, uses 8 bytes of the 64-byte line it loaded, and often misses the cache. Swapping the two inner loops fixes this.

Java
// i-j-k: inner loop walks down a column of B (cache-unfriendly)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
double sum = 0;
for (int k = 0; k < n; k++) sum += a[i][k] * b[k][j]; // b[k][j]: new row each step
c[i][j] = sum;
}
// i-k-j: inner loop walks along rows of B and C (sequential)
for (int i = 0; i < n; i++) {
double[] ci = c[i];
for (int k = 0; k < n; k++) {
double aik = a[i][k];
double[] bk = b[k];
for (int j = 0; j < n; j++) ci[j] += aik * bk[j]; // contiguous: vectorizable
}
}
Each step and its trade-off
StepWhat it fixesCost
Loop order i-k-jColumn jumps, enables auto-vectorizationA few lines, same results
Flat double[] row-majorRow-array indirection, bounds checksIndex arithmetic i * n + j
Blocking (tiles of e.g. 64)Working set larger than cacheMore loops, tune tile size
Parallel rows (ForkJoin)Uses only one coreThreads shared with other work
Vector API or BLAS libraryNot using full SIMD or tuned kernelsIncubator flag or a native dependency
Each row is measured with JMH before moving to the next.

In the i-k-j version, the inner loop reads bk[j] and updates ci[j] for consecutive j, so every byte of each cache line is used and the hardware prefetcher can stream the rows. The loop is also a simple pattern that HotSpot's C2 compiler can auto-vectorize with SIMD instructions. On typical hardware this change alone is often several times faster; the exact factor depends on the CPU, so we measure it.

Notice a nice property for a pricing service: each C[i][j] still adds its products in the same order of k, so the results are bit-for-bit identical to the naive version. Reordering loops this way does not change the floating-point rounding.

3Flatten the Data and Block It

Storing a matrix as one double[] of length n x n, with element (i, j) at index i * n + j, removes the indirection through row arrays and keeps the whole matrix contiguous. It also makes it easy to pass the data to native libraries later.

Blocking, also called tiling, splits the matrices into small square tiles, for example 64 x 64 doubles, which is 32 KB per tile, and multiplies tile by tile. The point is reuse: once a tile of B is in cache, it is used for many rows of A before being evicted, instead of being reloaded from main memory for each row. The best tile size depends on the cache sizes of the production CPU, so we try a few values in a benchmark.

4Parallelize Across Rows

Once one core runs efficiently, we use the others. Rows of C are independent: computing row i only reads A and B and writes row i of C, so we can split rows among threads without locks.

Java
IntStream.range(0, n).parallel().forEach(i -> { // each task owns row i of c
int ci = i * n;
for (int k = 0; k < n; k++) {
double aik = a[ci + k];
int bk = k * n;
for (int j = 0; j < n; j++) c[ci + j] += aik * b[bk + j];
}
});

Parallel streams run on the common ForkJoinPool, which is shared by the whole JVM, so in a service that also handles other requests we would rather use a dedicated ForkJoinPool sized for this work. On 8 cores we might expect a large part of an 8x speedup, limited by memory bandwidth, which all cores share. We parallelize last because parallelizing a cache-unfriendly loop mostly makes all cores wait on memory together.

5The Vector API and Libraries

The Vector API (jdk.incubator.vector) lets us write SIMD code explicitly, such as computing 4 or 8 products per instruction with a fused multiply-add, instead of hoping the JIT vectorizes. In Java 25 it is still an incubator module, enabled with --add-modules jdk.incubator.vector, so its API can still change between releases; check your version. Note that fused multiply-add rounds once instead of twice, so results can differ from the scalar loop in the last bits, which a pricing team should know about.

The biggest gains usually come from not writing the kernel at all. Mature Java libraries such as EJML implement blocked multiplication, and native BLAS libraries such as OpenBLAS or Intel MKL have kernels tuned per CPU that reach a large fraction of the hardware's peak. Since Java 22, the Foreign Function and Memory API lets us call such a library and share off-heap memory without writing JNI glue. That gives near-C performance while the service stays in Java.

6Deciding With Numbers

The decision should rest on measurements, not on language reputation. I would set up a JMH benchmark with the real matrix size, record the naive time, and then record each step. A plausible sequence on a modern server is: the naive loop takes tens of seconds, the loop order fix brings it to a few seconds, blocking and flattening improve it further, parallelism divides by a large part of the core count, and a BLAS call gets close to the hardware's peak. Each of those numbers must come from our own hardware.

Then we compare with the latency target. If the tuned Java or the library call meets it, a C++ rewrite would add a second language to hire for and support, a native build per platform, a JNI or FFM boundary with its own failure modes, such as a crash taking down the JVM, and none of the speedup, because the C++ code would face the same memory issues and would end up calling the same BLAS. A rewrite makes sense only if measurements show a gap that Java and the libraries cannot close, and even then calling an existing native library is usually cheaper than rewriting the service.

7Follow-up questions

How would you verify that the JIT vectorized your loop?

I would look at the machine code. With JMH, the perfasm profiler (-prof perfasm, on Linux with perf) shows the hottest assembly, and I check for packed SIMD instructions such as vmulpd or vfmadd231pd on vector registers, instead of scalar ones like vmulsd. Without JMH, -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly prints compiled code, but it needs the hsdis disassembler library installed. The benchmark itself is also evidence: a sudden several-fold jump when changing loop order or element type often means vectorization started or stopped.

Why not just use parallel streams on the original code?

Because the original loop is limited by memory latency, not by CPU work. Running it on 8 cores multiplies the number of cache misses in flight but leaves each core mostly waiting, and the shared memory bandwidth limits the gain. Fixing the access pattern first makes each core fast, and then parallelism multiplies a good result instead of a bad one.

8Conclusion

In this answer, we saw that a naive i-j-k matrix multiplication in Java is slow mainly because its inner loop jumps down columns of B and misses the cache. Changing the order to i-k-j, flattening into a row-major double[], blocking for cache sizes and then parallelizing across rows each give measurable gains, and the Vector API or a native BLAS called through the Foreign Function and Memory API can approach the hardware's peak. The decision about C++ should follow JMH measurements against the latency target, counting the cost of a second language, a native build and a JNI or FFM boundary, which usually makes the Java options the better choice.

What to say in the interviewAbout 100 seconds aloud

Open with

I would not start with a rewrite, because the naive loop is slow for reasons that would follow us to C++. In the i-j-k order, the inner loop reads b k j, which jumps to a different row array at every step, so almost every read misses the cache.

Then, if they want more

First I would switch to i-k-j, where the inner loop walks along a row of B and a row of C. That uses every byte of each cache line, lets the JIT auto-vectorize, and keeps the results bit-for-bit the same because each sum is still accumulated in the same order. That alone is often several times faster.

Next I would store each matrix as one flat double array in row-major order and add blocking, tiles of something like 64 by 64, so the data I reuse stays in cache. Then, with one core running well, I would parallelize across rows of C with a dedicated ForkJoinPool, since rows are independent.

Beyond that, the Vector API gives explicit SIMD, though it is still incubating in Java 25, and libraries like EJML, or a native BLAS called through the Foreign Function and Memory API, get close to the hardware's peak without leaving Java. I would measure every step with JMH on production-like hardware and compare with the latency target.

A C++ rewrite adds a second language, native builds and a JNI or FFM boundary, and it would probably end up calling the same BLAS, so I would only consider it if the measurements show a gap Java cannot close.

About this answer

Last updated
12 November 2026
Versions it names
Java 25, Java 22
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. 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 Java pricing service multiplies 2,000 x 2,000 double matrices for each risk...": https://scrivio-interview-library.netlify.app/java/coding-problems/5568c6d8d7/