wang-jiahua commented on code in PR #10485:
URL: https://github.com/apache/rocketmq/pull/10485#discussion_r3400418131


##########
remoting/src/main/java/org/apache/rocketmq/remoting/metrics/RemotingMetricsManager.java:
##########
@@ -86,6 +96,44 @@ public List<Pair<InstrumentSelector, ViewBuilder>> 
getMetricsView() {
         return Lists.newArrayList(new Pair<>(selector, viewBuilder));
     }
 
+    public Attributes getOrBuildAttributes(int requestCode, int responseCode,
+        boolean isLongPolling, String result) {
+        int resultIdx;
+        if (RESULT_SUCCESS.equals(result)) resultIdx = 0;
+        else if (RESULT_ONEWAY.equals(result)) resultIdx = 1;
+        else if (RESULT_WRITE_CHANNEL_FAILED.equals(result)) resultIdx = 2;
+        else if (RESULT_CANCELED.equals(result)) resultIdx = 3;
+        else resultIdx = -1;
+
+        if (resultIdx < 0) {
+            return buildAttributes(requestCode, responseCode, isLongPolling, 
result);
+        }
+
+        long key = ((long) requestCode << 19)
+            | ((long) (responseCode & 0xFFFF) << 3)
+            | (isLongPolling ? 4L : 0L)
+            | resultIdx;
+        Attributes cached = this.lastCachedAttrs;
+        if (cached != null && key == this.lastAttrsCacheKey) {
+            return cached;
+        }
+        Attributes attrs = attributesCache.computeIfAbsent(key,
+            k -> buildAttributes(requestCode, responseCode, isLongPolling, 
result));
+        this.lastAttrsCacheKey = key;
+        this.lastCachedAttrs = attrs;
+        return attrs;

Review Comment:
   Acknowledged — this is an intentional trade-off documented in the design.
   
   The inline cache here is an **idempotent query** (same inputs always produce 
same output). A torn-read between `lastAttrsCacheKey` and `lastCachedAttrs` can 
only cause a single call to return a stale `Attributes` for a different key — 
it will be corrected on the very next call. The metrics error is bounded to ±1 
data point per torn-read event, negligible when aggregated per-minute.
   
   This is explicitly different from `RemotingCodeDistributionHandler` (same 
PR) which IS a counter accumulation and DOES use an immutable holder to prevent 
torn-read — because there, a torn-read permanently miscounts and is never 
self-corrected.
   
   The alternative (single immutable holder for the cache) would add an extra 
object allocation per cache miss. The current approach trades theoretical ±1 
imprecision for lower per-call overhead.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to