Skip to content

Use ThreadLocal caching for ExtendedRandom PRNG contexts - #1508

Open
taoliult wants to merge 3 commits into
IBM:java25from
taoliult:java25_securerandom_native_2
Open

Use ThreadLocal caching for ExtendedRandom PRNG contexts#1508
taoliult wants to merge 3 commits into
IBM:java25from
taoliult:java25_securerandom_native_2

Conversation

@taoliult

@taoliult taoliult commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator

Add ThreadLocal caching for native PRNG contexts used by ExtendedRandom. Each thread creates and reuses a PRNG context for supported DRBG algorithms.

This avoids repeated EXTRAND_create calls when instances are created frequently.

Benefits:

  • Reduce native allocation overhead
  • Reuse PRNG contexts per thread
  • Improve performance in RNG-heavy workloads

This PR is back-ported from PR #1255

@taoliult
taoliult force-pushed the java25_securerandom_native_2 branch 2 times, most recently from 235c7da to ffb4748 Compare June 16, 2026 17:29

@KostasTsiounis KostasTsiounis left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@jasonkatonica jasonkatonica left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

Add ThreadLocal caching for native PRNG contexts used by
ExtendedRandom. Each thread creates and reuses a PRNG
context for supported DRBG algorithms.

This avoids repeated EXTRAND_create calls when instances
are created frequently.

Benefits:
- Reduce native allocation overhead
- Reuse PRNG contexts per thread
- Improve performance in RNG-heavy workloads

Signed-off-by: Tao Liu <tao.liu@ibm.com>
ThreadLocal can cause native TCB context issues on z/OS. This
change bypasses ThreadLocal on z/OS by creating instance-specific
PRNG contexts, while other platforms continue using ThreadLocal
for performance.

Signed-off-by: Tao Liu <tao.liu@ibm.com>
@taoliult
taoliult force-pushed the java25_securerandom_native_2 branch from a1d1f7e to e21f469 Compare September 1, 2026 18:51
Avoid storing ThreadLocal-owned native PRNG context IDs in
ockPRNGContextId. The native context is owned by the
ThreadLocal PRNGContextPointer, so copying its raw context ID
into the ExtendedRandom instance can leave a stale pointer if
the creating thread exits and the ThreadLocal value is cleaned.

Resolve the ThreadLocal PRNGContextPointer in nextBytes()
instead, so each call uses the current thread's live context and
keeps the PRNGContextPointer strongly reachable during the native
call.

Keep ockPRNGContextId only for instance-owned contexts, such as
z/OS or after setSeed().
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.

4 participants