Skip to content

WW-5724 Hand out a clone of the cached MessageFormat - #1914

Open
lukaszlenart wants to merge 1 commit into
mainfrom
WW-5724-messageformat-clone
Open

WW-5724 Hand out a clone of the cached MessageFormat#1914
lukaszlenart wants to merge 1 commit into
mainfrom
WW-5724-messageformat-clone

Conversation

@lukaszlenart

Copy link
Copy Markdown
Member

Fixes WW-5724

AbstractLocalizedTextProvider caches MessageFormat instances by pattern and locale and returned the cached instance itself from buildMessageFormat. MessageFormat is not thread-safe, so concurrent callers rendering the same message formatted through one shared instance; with a date or time sub-format that produced output for the wrong argument or an exception.

buildMessageFormat now returns a clone of the cached instance, so the cached entry is only ever a template and is never formatted directly. MessageFormat.clone() deep-copies the sub-formats. The pattern-parsing cache is kept.

Two tests added to StrutsLocalizedTextProviderTest: one asserts two lookups of the same pattern no longer return the same instance while the cache still holds one entry; the other renders a {0,date,short} message from four threads with distinct dates and asserts every output matches its own argument. Both failed before the change.

Why clone rather than the alternatives: building a fresh instance per call drops the parsing cache the WW-5540 work relies on, and synchronizing on the shared instance serializes all rendering. Measured over 1.2M renders on JDK 17, cloning was the cheapest of the three (176 ms, against 409 ms fresh-per-call and 556 ms synchronized).

No configuration or API change. Applies to both maintenance lines; the 6.x backport follows.

🤖 Generated with Claude Code

AbstractLocalizedTextProvider caches MessageFormat instances by pattern
and locale and returned the cached instance itself from
buildMessageFormat. MessageFormat is not thread-safe, so concurrent
callers rendering the same message formatted through one shared
instance; with a date or time sub-format that produced output for the
wrong argument or an exception.

buildMessageFormat now returns a clone of the cached instance, so the
cached entry is only ever a template and is never formatted directly.
MessageFormat.clone() deep-copies the sub-formats. The pattern-parsing
cache is kept; measured against a fresh instance per call and against
synchronizing on the shared instance, cloning is the cheapest of the
three.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@sonarqubecloud

Copy link
Copy Markdown

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.

1 participant