8000 opt: replace Random with ThreadLocalRandom by funky-eyes · Pull Request #373 · sofastack/sofa-bolt · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

opt: replace Random with ThreadLocalRandom #373

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 21, 2025

Conversation

funky-eyes
Copy link
Contributor
@funky-eyes funky-eyes commented Apr 2, 2025

fixes: #372

Summary by CodeRabbit

  • Refactor
    • Enhanced the mechanism for random value generation used in connection selections and data generation. This update improves performance and thread-safety in concurrent operations while maintaining existing functionality.

Copy link
coderabbitai bot commented Apr 2, 2025

Walkthrough

The changes update the random number generation mechanism across multiple modules. In all affected files, the usage of the Random class has been replaced with ThreadLocalRandom. This change removes the need for maintaining individual Random instances, replacing them with thread-local calls for generating random indices or random bytes. The functional behavior remains the same, but the implementation is now more compatible with concurrency and JDK21’s accessibility requirements.

Changes

Files Change Summary
src/main/java/com/alipay/remoting/RandomSelectStrategy.java
src/main/java/com/alipay/remoting/ScheduledDisconnectStrategy.java
Removed explicit Random instance fields and updated methods to use ThreadLocalRandom.current().nextInt(...) for random index selection.
src/test/java/com/alipay/remoting/benchmark/BenchmarkClient.java Replaced the instantiation of a new Random with ThreadLocalRandom.current().nextBytes(...) to generate random bytes in the static BYTES array.
src/test/java/com/alipay/remoting/rpc/common/RequestBody.java
src/test/java/com/alipay/remoting/rpc/userprocessor/multiinterestprocessor/RequestBodyC1.java
src/test/java/com/alipay/remoting/rpc/userprocessor/multiinterestprocessor/RequestBodyC2.java
Removed the Random instance variables and updated random byte generation calls to use ThreadLocalRandom.current().nextBytes(...), eliminating unnecessary state.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant ThreadLocalRandom
    Caller->>ThreadLocalRandom: current()
    Caller->>ThreadLocalRandom: nextInt(size) / nextBytes(data)
    ThreadLocalRandom-->>Caller: Generated random value
Loading

Assessment against linked issues

Objective Addressed Explanation
jdk21 demo测试中Random 不可用 (#372)

Poem

I'm a hopping rabbit, quick on my feet,
No more Random woes, my code's now neat!
ThreadLocal magic dances in every thread,
JDK21 troubles left unsaid.
With each leap, our bugs retreat,
Code carrots crunch, and joy's complete!
Happy hops in the digital street!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between db68f89 and 03098fe.

📒 Files selected for processing (6)
  • src/main/java/com/alipay/remoting/RandomSelectStrategy.java (2 hunks)
  • src/main/java/com/alipay/remoting/ScheduledDisconnectStrategy.java (2 hunks)
  • src/test/java/com/alipay/remoting/benchmark/BenchmarkClient.java (2 hunks)
  • src/test/java/com/alipay/remoting/rpc/common/RequestBody.java (2 hunks)
  • src/test/java/com/alipay/remoting/rpc/userprocessor/multiinterestprocessor/RequestBodyC1.java (2 hunks)
  • src/test/java/com/alipay/remoting/rpc/userprocessor/multiinterestprocessor/RequestBodyC2.java (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: build (11)
  • GitHub Check: build (21)
  • GitHub Check: build (17)
  • GitHub Check: build (8)
🔇 Additional comments (12)
src/test/java/com/alipay/remoting/benchmark/BenchmarkClient.java (2)

22-22: Nice use of ThreadLocalRandom import

Good job replacing Random with ThreadLocalRandom for improved thread-safety and performance in concurrent environments.


63-63: Great optimization using ThreadLocalRandom

Excellent change replacing new Random().nextBytes(BYTES) with ThreadLocalRandom.current().nextBytes(BYTES). This eliminates potential contention in multi-threaded environments and aligns with modern Java concurrency best practices.

src/test/java/com/alipay/remoting/rpc/userprocessor/multiinterestprocessor/RequestBodyC2.java (2)

19-19: Good ThreadLocalRandom import

Nice job replacing Random with ThreadLocalRandom import, which is more efficient for concurrent environments.


63-63: Well implemented ThreadLocalRandom usage

Great improvement replacing r.nextBytes(this.body) with ThreadLocalRandom.current().nextBytes(this.body). This removes the need for maintaining a Random instance variable while improving thread safety and performance.

src/main/java/com/alipay/remoting/RandomSelectStrategy.java (2)

21-21: Appropriate ThreadLocalRandom import

Good replacement of Random with ThreadLocalRandom import for better concurrency handling.


98-98: Excellent ThreadLocalRandom implementation

Great job replacing this.random.nextInt(size) with ThreadLocalRandom.current().nextInt(size). This change:

  1. Eliminates the need for a class-level Random instance
  2. Improves performance in concurrent scenarios
  3. Reduces contention when multiple threads are selecting connections

This is particularly important for a connection selection strategy that may be frequently called in a server application.

src/test/java/com/alipay/remoting/rpc/userprocessor/multiinterestprocessor/RequestBodyC1.java (2)

19-19: Good ThreadLocalRandom import

Nice job switching from Random to ThreadLocalRandom import for better thread-safety.


60-60: Well implemented ThreadLocalRandom usage

Excellent change replacing r.nextBytes(this.body) with ThreadLocalRandom.current().nextBytes(this.body). This removes the need for a class-level Random instance while improving performance in multi-threaded environments.

src/main/java/com/alipay/remoting/ScheduledDisconnectStrategy.java (2)

23-23: Import change looks good.

The addition of ThreadLocalRandom import is appropriate for the code changes made in this file.


104-105: Great optimization using ThreadLocalRandom!

Replacing Random with ThreadLocalRandom is a solid improvement:

  • Eliminates contention that can occur with a shared Random instance
  • More efficient in concurrent environments
  • Reduces overhead in multi-threaded scenarios
  • Aligns with modern Java best practices

The functional behavior remains unchanged while improving thread safety and performance.

src/test/java/com/alipay/remoting/rpc/common/RequestBody.java (2)

20-20: Import change looks good.

The addition of ThreadLocalRandom import is appropriate for the changes in this file.


65-65: Good optimization for random bytes generation.

Replacing r.nextBytes(this.body) with ThreadLocalRandom.current().nextBytes(this.body) is a good improvement:

  • Eliminates the need for a class-level Random instance
  • Provides better performance in concurrent test scenarios
  • Maintains the same functional behavior
  • Follows consistent pattern with other changes in the PR

This change aligns with the overall goal of optimizing random number generation in the codebase.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@funky-eyes
Copy link
Contributor Author

@OrezzerO @EvenLjj PTAL

Copy link
Collaborator
@OrezzerO OrezzerO left a comment

Choose a reason for hiding this comment

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

LGTM

@funky-eyes funky-eyes closed this Apr 2, 2025
@funky-eyes funky-eyes reopened this Apr 2, 2025
@funky-eyes
Copy link
Contributor Author

@chuailiwu PTAL

@EvenLjj EvenLjj merged commit 5c52880 into sofastack:master Apr 21, 2025
10 of 13 checks passed
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.

jdk21 demo测试中Random 不可用
3 participants
0