Class RequestContextMDCBridge

java.lang.Object
com.loomcache.server.context.RequestContextMDCBridge

public final class RequestContextMDCBridge extends Object
Bridge to synchronize ScopedValue-based RequestContext with SLF4J's MDC.

Purpose

This class demonstrates the gradual migration path from ThreadLocal-based MDC to ScopedValue-based RequestContext. It provides utilities to: - Sync RequestContext values to MDC for compatibility with existing loggers - Demonstrate how to gradually adopt ScopedValues in the codebase

Migration Strategy

  1. Step 1: Introduce RequestContext alongside MDC (this bridge)
  2. Step 2: Use ScopedValue.run() or call() to bind context
  3. Step 3: Optionally sync to MDC via this bridge for logger compatibility
  4. Step 4: Update logback.xml to consume RequestContext instead of MDC
  5. Step 5: Remove MDC.put/remove calls once all logging uses RequestContext

Usage Example

  // Old way (ThreadLocal/MDC):
  MDC.put("nodeId", "node-1");
  MDC.put("requestId", "123");
  try {
      // ... operation ...
  } finally {
      MDC.remove("nodeId");
      MDC.remove("requestId");
  }

  // New way (ScopedValue + bridge):
  var context = RequestContext.newScope()
          .nodeId("node-1")
          .correlationId(123L);
  context.run(() -> {
      RequestContextMDCBridge.syncToMDC();  // Optional: for logger compatibility
      // ... operation ...
      RequestContextMDCBridge.clearMDC();
  });
Since:
1.0
See Also:
  • Constructor Details

    • RequestContextMDCBridge

      public RequestContextMDCBridge()
  • Method Details

    • syncToMDC

      public static void syncToMDC()
      Synchronize current RequestContext values to MDC.

      Call this within a RequestContext.newScope().run() block to make context available to loggers that expect MDC values.

        RequestContext.newScope()
                .nodeId("node-1")
                .correlationId(123L)
                .run(() -> {
                    RequestContextMDCBridge.syncToMDC();
                    log.info("Processing request");  // MDC values available
                    RequestContextMDCBridge.clearMDC();
                });
      
    • clearMDC

      public static void clearMDC()
      Clear all MDC values that were set by syncToMDC().

      Call this in a finally block or at the end of a scope to clean up MDC.

    • hasContext

      public static boolean hasContext()
      Check if any RequestContext values are currently bound.
      Returns:
      true if at least one context value is set