Skip to content

perf(sheet): recycle CellWriteHandlerContext across cells of a write - #1209

Draft
GOODBOY008 wants to merge 1 commit into
apache:mainfrom
GOODBOY008:perf/write-alloc-pr3
Draft

GOODBOY008 wants to merge 1 commit into
apache:mainfrom
GOODBOY008:perf/write-alloc-pr3

Conversation

@GOODBOY008

@GOODBOY008 GOODBOY008 commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

Summary

Recycle the CellWriteHandlerContext across all cells of a write session instead of allocating a fresh one per cell — Tomcat-style owner-scoped recycling (the same pattern org.apache.catalina.connector.Request uses): one mutable carrier per writer, reset at every cell boundary, no pool, no statics, no thread-locals.

JFR allocation profiling (jdk.ObjectAllocationSample, byte-weighted, MEDIUM XLSX write) attributes ~12% of write-side allocation bytes to this single allocation site (656 MB in the sampled profile) — the largest fesod-internal write allocation; only the POI/xmlbeans serialization layer above it allocates more.

What changes

  • CellWriteHandlerContext.reset(...) — re-initializes every field to the state a freshly built context would have: the per-cell arguments plus nulls for the fields only some write paths ever set (targetCellDataType CSV branch, ignoreFillStyle multi-variable fill, the converter/originalValue family). The class javadoc documents the contract: the context is only valid for the duration of one cell's handler chain.
  • CellWriteHandlerContextRecycler (new, ~100 lines) — hosts the single session instance and owns the guard rails:
    • renew(...) returns the recycled instance reset for the next cell; while that instance is still in flight (a nested write on the same writer inside a cell callback) it falls back to a fresh allocation instead of resetting the live one — worst case degrades to today's behavior, never corrupts.
    • cellCompleted(context) clears the in-flight mark on an identity match, so a nested write completing cannot free the outer cell's instance.
    • release() drops the instance when the session finishes.
  • Wiring — the recycler is created in WriteContextImpl.initCurrentWorkbookHolder and hosted on the WriteWorkbookHolder (following the existing workbookWriteHandlerContext precedent); executors cache it in a constructor-initialized field. finish(boolean onException) releases it at the top, so no Row/Cell references survive a closed writer — and because ExcelBuilderImpl already routes exceptions to finish(true), a session that dies mid-cell (e.g. a caught ExcelWriteDataConvertException) also detaches the instance. Note that exception snapshots row/column/cellData/property into its parent at construction.
  • All five cell-producing sites migrate (add ×3, fill, header row); each is a two-line change: factory call → renew(...), plus cellCompleted(...) after afterCellDispose. WriteHandlerUtils.createCellWriteHandlerContext stays unchanged and public.

Compatibility

No API change (only additive: reset and the recycler class). Handlers now receive a reused instance instead of a fresh one per cell — the documented contract (valid only during the callback, do not retain or key maps on it) matches what Tomcat documents for recycled request objects. Built-in handlers were audited on this baseline: none retain the context.

Benchmark

Same-machine A/B (Apple M1, Zulu JDK 17; FesodBenchmark.write, MEDIUM = 10,000 rows × 20 columns ≈ 200 K cells; avgt mode, -prof gc, 3 forks, 2×2 s warmup, 5×2 s measurement, n = 15 per config; merge base 2c1e4b22 vs this branch, both shaded jars built fresh and the PR jar verified to contain the recycler):

Benchmark alloc/op before alloc/op after Δ alloc avgt before avgt after Δ time
write, XLSX 208.32 MB/op 190.64 MB/op −8.5% 212.88 ± 1.62 ms/op 215.39 ± 4.18 ms/op within noise
write, CSV 184.82 MB/op 167.22 MB/op −9.5% 47.11 ± 0.70 ms/op 47.18 ± 0.87 ms/op within noise

The per-cell arithmetic confirms the mechanism: −88 B/cell on both formats — exactly one CellWriteHandlerContext (18 reference fields + object header), matching the design estimate. gc.alloc.rate.norm is deterministic (±0.001% across measurement iterations), so the allocation deltas sit hundreds of standard deviations from noise. Wall-clock is unchanged within the confidence intervals: this change targets allocation rate (GC pressure on sustained write workloads), not per-op latency, and the numbers show precisely that.

Tests

mvn -pl fesod-sheet clean verify -Dmaven.test.skip=false (root pom defaults to skipping tests): 966 tests green, 8 new —

  • reset-equivalence: poison every field of a used context, reset, assert field-for-field equality with a fresh factory-built one (fails the day a field is added without updating reset)
  • cross-cell isolation of the conditionally-set fields (targetCellDataType, ignoreFillStyle, …)
  • session reuse, nested-write fallback, release() semantics
  • end-to-end across XLSX/XLS/CSV: a recording handler asserts every afterCellDispose sees exactly its own cell's state, and that all cells (header included) went through one recycled instance

Signed-off-by: gongzhongqiang [email protected]

Copilot AI balanced review requested due to automatic review settings October 9, 2026 15:48

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@GOODBOY008
GOODBOY008 force-pushed the perf/write-alloc-pr3 branch 2 times, most recently from e99dbfc to 784a860 Compare October 10, 2026 01:54
@GOODBOY008
GOODBOY008 marked this pull request as draft October 10, 2026 02:07
@GOODBOY008
GOODBOY008 force-pushed the perf/write-alloc-pr3 branch 2 times, most recently from 3562ab8 to c74df90 Compare October 10, 2026 14:05
The write path allocated a fresh CellWriteHandlerContext for every
cell; JFR allocation profiling (jdk.ObjectAllocationSample,
byte-weighted) attributed ~12% of write-side allocation bytes to this
single site — the largest fesod-internal write allocation.

Recycle it Tomcat-style instead: the write session owns one instance
that is reset at every cell boundary.

- CellWriteHandlerContext.reset(...) restores every field to the state
  a freshly built context would have, including the fields only some
  write paths set (targetCellDataType, ignoreFillStyle)
- the new CellWriteHandlerContextRecycler hosts the instance on the
  WriteWorkbookHolder (one per writer) and guards it: a nested write on
  the same writer falls back to a fresh context rather than resetting
  the live one, and release() drops the instance when the session
  finishes (also on exception) so no Row/Cell references survive a
  closed writer
- all five cell-producing sites migrate (add x3, fill, header row);
  WriteHandlerUtils.createCellWriteHandlerContext stays unchanged
- the context contract is documented on the class: it is only valid
  for the duration of one cell's handler chain — handlers must not
  retain it beyond afterCellDispose (the same contract Tomcat
  documents for recycled request objects)

Signed-off-by: gongzhongqiang <[email protected]>
@GOODBOY008
GOODBOY008 force-pushed the perf/write-alloc-pr3 branch from c74df90 to 4c1ec0e Compare October 10, 2026 14:33
@GOODBOY008 GOODBOY008 changed the title perf(sheet): cut per-cell allocation on the write hot path perf(sheet): recycle CellWriteHandlerContext across cells of a write Oct 10, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants