Skip to content

support custom UserThreadPool for interface method #1500

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

EvenLjj
Copy link
Collaborator

@EvenLjj EvenLjj commented Jul 24, 2025

support custom UserThreadPool for interface method

Summary by CodeRabbit

  • New Features

    • Enhanced management of user-defined thread pools, allowing assignment at both the service and individual method levels.
    • Introduced a mechanism for dynamic selection of executors based on request metadata, improving flexibility in request processing.
    • Added a method to access the internal server processor for extended control.
  • Bug Fixes

    • Improved thread pool selection logic to ensure correct executor assignment when both service-level and method-level thread pools are configured.
  • Tests

    • Added comprehensive tests to verify the correct selection and registration of user thread pools at both service and method levels, including custom selection scenarios.
  • Refactor

    • Streamlined internal logic by relocating and updating executor selection components for better maintainability.

@sofastack-cla sofastack-cla bot added cla:yes CLA is ok size/L labels Jul 24, 2025
Copy link
Contributor

coderabbitai bot commented Jul 24, 2025

Walkthrough

This update introduces method-level user thread pool management in UserThreadPoolManager, enabling thread pool registration and retrieval by both service and method name. The UserThreadPoolSelector logic is refactored into a new class, with corresponding tests added. The BoltServer exposes its processor, and tests validate the new thread pool selection behaviors.

Changes

File(s) Change Summary
core/api/src/main/java/com/alipay/sofa/rpc/config/UserThreadPoolManager.java Added support for registering, retrieving, and unregistering user thread pools by service and method.
core/api/src/test/java/com/alipay/sofa/rpc/config/UserThreadPoolManagerTest.java Extended tests to cover method-level thread pool registration and retrieval.
remoting/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/BoltServer.java Added getter for internal boltServerProcessor.
remoting/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/BoltServerProcessor.java Removed inner class UserThreadPoolSelector and related logic; updated constructor accordingly.
remoting/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/UserThreadPoolSelector.java New class implementing user thread pool selection logic for Bolt requests.
remoting/remoting-bolt/src/test/java/com/alipay/sofa/rpc/server/bolt/UserThreadPoolSelectorTest.java New test class for verifying user thread pool selection logic and custom selector scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant BoltServer
    participant BoltServerProcessor
    participant UserThreadPoolSelector
    participant UserThreadPoolManager

    Client->>BoltServer: Send request (with service & method)
    BoltServer->>BoltServerProcessor: Process request
    BoltServerProcessor->>UserThreadPoolSelector: select(requestClass, requestHeader)
    UserThreadPoolSelector->>UserThreadPoolManager: getUserThread(service, method)
    alt Thread pool found
        UserThreadPoolManager-->>UserThreadPoolSelector: Return UserThreadPool
        UserThreadPoolSelector-->>BoltServerProcessor: Return user executor
    else Not found
        UserThreadPoolSelector-->>BoltServerProcessor: Return default executor
    end
    BoltServerProcessor-->>BoltServer: Execute request with selected executor
    BoltServer-->>Client: Return response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Suggested labels

size/S

Poem

A rabbit hopped through thread and pool,
Now method names are part of the rule!
Selectors refactored, logic anew,
Tests ensure it all rings true.
BoltServer listens, ready to serve,
With user executors on every curve—
Hooray for code that’s nimble and cool! 🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 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 5166773 and c9fcc11.

📒 Files selected for processing (3)
  • core/api/src/main/java/com/alipay/sofa/rpc/config/UserThreadPoolManager.java (4 hunks)
  • remoting/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/UserThreadPoolSelector.java (1 hunks)
  • remoting/remoting-bolt/src/test/java/com/alipay/sofa/rpc/server/bolt/UserThreadPoolSelectorTest.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • remoting/remoting-bolt/src/test/java/com/alipay/sofa/rpc/server/bolt/UserThreadPoolSelectorTest.java
  • core/api/src/main/java/com/alipay/sofa/rpc/config/UserThreadPoolManager.java
  • remoting/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/UserThreadPoolSelector.java
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build
  • GitHub Check: sca
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Nitpick comments (4)
remoting/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/BoltServer.java (1)

327-333: Consider the implications of exposing internal state

While this getter enables external configuration of the processor's executor selector, exposing the internal BoltServerProcessor instance breaks encapsulation and could lead to thread-safety issues if the processor is modified after server initialization.

Consider alternatives such as:

  1. Adding a method to set the executor selector directly on BoltServer
  2. Making the processor immutable or returning a defensive copy
  3. Documenting thread-safety guarantees
core/api/src/test/java/com/alipay/sofa/rpc/config/UserThreadPoolManagerTest.java (1)

59-63: Enhance test coverage and organization

While the basic functionality is tested, consider:

  1. Creating a separate test method for method-level thread pool testing
  2. Adding edge case tests (null parameters, empty strings, concurrent access)
  3. Testing the interaction between service-level and method-level pools
+@Test
+public void testMethodLevelUserThreadPool() {
+    // Test basic functionality
+    UserThreadPool methodUserThreadPool = new UserThreadPool();
+    UserThreadPoolManager.registerUserThread("service1", "method1", methodUserThreadPool);
+    Assert.assertEquals(methodUserThreadPool, UserThreadPoolManager.getUserThread("service1", "method1"));
+    
+    // Test that service-level pool doesn't interfere
+    Assert.assertNull(UserThreadPoolManager.getUserThread("service1"));
+    
+    // Test unregistration
+    UserThreadPoolManager.unRegisterUserThread("service1", "method1");
+    Assert.assertNull(UserThreadPoolManager.getUserThread("service1", "method1"));
+    
+    // Test edge cases
+    UserThreadPoolManager.registerUserThread("", "method", new UserThreadPool());
+    Assert.assertNotNull(UserThreadPoolManager.getUserThread("", "method"));
+}
core/api/src/main/java/com/alipay/sofa/rpc/config/UserThreadPoolManager.java (1)

69-74: Consider optimizing synchronization strategy

Using synchronized on all methods creates a potential bottleneck. Since ConcurrentHashMap is already thread-safe, consider:

  1. Using double-checked locking for initialization
  2. Removing synchronization from read operations
  3. Using ConcurrentHashMap.computeIfAbsent() for atomic operations
-public static synchronized void registerUserThread(String service, String methodName, UserThreadPool userThreadPool) {
+public static void registerUserThread(String service, String methodName, UserThreadPool userThreadPool) {
     if (userThreadMap == null) {
-        userThreadMap = new ConcurrentHashMap<String, UserThreadPool>();
+        synchronized (UserThreadPoolManager.class) {
+            if (userThreadMap == null) {
+                userThreadMap = new ConcurrentHashMap<String, UserThreadPool>();
+            }
+        }
     }
     userThreadMap.put(service + SPLIT + methodName, userThreadPool);
 }

Also applies to: 93-97

remoting/remoting-bolt/src/test/java/com/alipay/sofa/rpc/server/bolt/UserThreadPoolSelectorTest.java (1)

84-98: Consider adding type safety to the header casting.

The helper method correctly demonstrates custom executor selector configuration. However, the unchecked cast on line 87 could be made more robust.

Consider this improvement for better type safety:

 boltServerProcessor.setExecutorSelector((requestClass, requestHeader) -> {
-    Map<String, String> headerMap = (Map<String, String>) requestHeader;
+    if (!(requestHeader instanceof Map)) {
+        return boltServer.getBizExecutor();
+    }
+    @SuppressWarnings("unchecked")
+    Map<String, String> headerMap = (Map<String, String>) requestHeader;
     if (headerMap.containsKey("customThreadPool")) {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d7d0995 and 5166773.

📒 Files selected for processing (6)
  • core/api/src/main/java/com/alipay/sofa/rpc/config/UserThreadPoolManager.java (4 hunks)
  • core/api/src/test/java/com/alipay/sofa/rpc/config/UserThreadPoolManagerTest.java (1 hunks)
  • remoting/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/BoltServer.java (1 hunks)
  • remoting/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/BoltServerProcessor.java (1 hunks)
  • remoting/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/UserThreadPoolSelector.java (1 hunks)
  • remoting/remoting-bolt/src/test/java/com/alipay/sofa/rpc/server/bolt/UserThreadPoolSelectorTest.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build
  • GitHub Check: sca
🔇 Additional comments (6)
remoting/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/BoltServerProcessor.java (1)

91-91: LGTM!

The instantiation of the new UserThreadPoolSelector class with the default executor is correct and follows the intended design.

remoting/remoting-bolt/src/test/java/com/alipay/sofa/rpc/server/bolt/UserThreadPoolSelectorTest.java (5)

1-35: LGTM! Clean imports and standard license header.

The package structure and imports are well-organized and include all necessary dependencies for testing the UserThreadPoolSelector functionality.


48-55: LGTM! Setup correctly demonstrates interface and method-level thread pool registration.

The beforeClass method properly initializes both UserThreadPool instances and registers them at different granularities (interface-level and method-level), which aligns perfectly with the PR objectives for supporting custom UserThreadPool for interface methods.


57-69: Excellent test coverage of the UserThreadPoolSelector logic.

This test method comprehensively validates the thread pool selection hierarchy:

  1. Method-level selection takes precedence
  2. Falls back to interface-level when method is unregistered
  3. Falls back to default executor when service is unregistered

The test scenarios effectively demonstrate the new functionality introduced by this PR.


71-82: LGTM! Good validation of custom executor selector functionality.

This test effectively demonstrates the extensibility of the thread pool selection mechanism, showing how users can implement custom selection logic based on their own header keys. This aligns well with the PR's goal of providing flexible thread pool management.


100-107: LGTM! Clean teardown of thread pool registrations.

The cleanup method properly unregisters the thread pools and clears static references, ensuring no memory leaks from the thread pool manager. The cleanup matches the setup performed in beforeClass().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant