From dc1f4f3a64aa3f4c588f5a4701316bea4d316acd Mon Sep 17 00:00:00 2001 From: Siddhant Deshmukh Date: Wed, 13 Mar 2024 11:33:23 -0700 Subject: [PATCH] Create counter atomically Signed-off-by: Siddhant Deshmukh --- .../opensearch/action/search/SearchQueryCounters.java | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/server/src/main/java/org/opensearch/action/search/SearchQueryCounters.java b/server/src/main/java/org/opensearch/action/search/SearchQueryCounters.java index 27270f8465ef5..a8a7e352b89dc 100644 --- a/server/src/main/java/org/opensearch/action/search/SearchQueryCounters.java +++ b/server/src/main/java/org/opensearch/action/search/SearchQueryCounters.java @@ -55,20 +55,16 @@ public SearchQueryCounters(MetricsRegistry metricsRegistry) { public void incrementCounter(QueryBuilder queryBuilder, int level) { String uniqueQueryCounterName = queryBuilder.getName(); - if (!nameToQueryTypeCounters.contains(uniqueQueryCounterName)) { - createQueryCounter(uniqueQueryCounterName); - } - - Counter counter = nameToQueryTypeCounters.getOrDefault(uniqueQueryCounterName, otherQueryCounter); + Counter counter = nameToQueryTypeCounters.computeIfAbsent(uniqueQueryCounterName, k -> createQueryCounter(k)); counter.add(1, Tags.create().addTag(LEVEL_TAG, level)); } - private void createQueryCounter(String counterName) { + private Counter createQueryCounter(String counterName) { Counter counter = metricsRegistry.createCounter( "search.query.type." + counterName + ".count", "Counter for the number of top level and nested " + counterName + " search queries", UNIT ); - nameToQueryTypeCounters.put(counterName, counter); + return counter; } }