Core Java and OOP · Scenario
A nightly CSV job that got very slow
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
A nightly job builds a settlement CSV of yesterday's transactions and uploads it to the bank. A year ago it took five minutes. Now there are four times as many rows and it takes almost three hours, and the CPU and GC graphs go wild while it runs. What do you look at?
Then
Follow-ups the interviewer asks next
- What do you check first?
- The code builds the file with
csv = csv + line + "\n"in a loop. Why does four times the rows make it far more than four times slower? - Would StringBuffer help?
- The bank's cut-off is 6 am and tonight's run is already late. What do you do right now?
- What's the proper fix?
- Java 9 changed how
+on strings compiles. Doesn't that fix this loop? - How would you catch this before production?
The answer
What a strong answer covers
- Measure each phase: database read, building the file, upload. Look at allocation rate and GC in JFR or the GC log.
+=in a loop copies the whole string so far on every row, so total work grows with the square of the rows: four times the rows is about sixteen times the copying, plus a new large array each time (garbage, GC, and in G1, humongous allocations once the string passes half a region).- StringBuilder keeps one growing buffer (size it up front if you know roughly how big). StringBuffer is the same but synchronized: no help here.
- Better still: don't hold the whole file in memory. Read rows with a cursor or fetch size and write through a BufferedWriter to a file or straight into the upload stream.
- Java 9 (JEP 280) compiles one
a + b + cexpression into a single efficient call. Each loop iteration is still a new copy. - Tonight: the one-line StringBuilder fix is low-risk; run it by hand, and warn the operations team and the bank contact if the cut-off is at risk.
- Prevent: a test with production-sized data, a job-duration metric with an alert, and a static-analysis rule for string concatenation in loops.
The red pen
Common traps
Avoid:"give the pod more memory and CPU"; "use StringBuffer because it's thread-safe"; "the JIT optimises += in loops".
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.