diff --git a/broker/src/test/java/org/apache/rocketmq/broker/BrokerStatsManagerTest.java b/broker/src/test/java/org/apache/rocketmq/broker/BrokerStatsManagerTest.java index 6268865b1adda4f04e90d49bddc1d5f5fdad648d..1948b0bf77e0096402da4906f7775347b7833b8b 100644 --- a/broker/src/test/java/org/apache/rocketmq/broker/BrokerStatsManagerTest.java +++ b/broker/src/test/java/org/apache/rocketmq/broker/BrokerStatsManagerTest.java @@ -41,7 +41,14 @@ public class BrokerStatsManagerTest { } } - public AtomicLong test_unit() throws InterruptedException { + @Test + public void test_getAndCreateMomentStatsItem_multiThread() throws InterruptedException { + for (int i = 0; i < 5; i++) { + assertEquals(10, test_unit_moment().longValue()); + } + } + + private AtomicLong test_unit() throws InterruptedException { brokerStatsManager = new BrokerStatsManager("DefaultCluster"); executor = new ThreadPoolExecutor(100, 200, 10, TimeUnit.SECONDS, new ArrayBlockingQueue(10000), new ThreadFactoryImpl("testMultiThread")); @@ -62,6 +69,27 @@ public class BrokerStatsManagerTest { return brokerStatsManager.getStatsItem(TOPIC_PUT_NUMS, "topicTest").getValue(); } + private AtomicLong test_unit_moment() throws InterruptedException { + brokerStatsManager = new BrokerStatsManager("DefaultCluster"); + executor = new ThreadPoolExecutor(100, 200, 10, TimeUnit.SECONDS, + new ArrayBlockingQueue(10000), new ThreadFactoryImpl("testMultiThread")); + for (int i = 0; i < 10000; i++) { + executor.submit(new Runnable() { + @Override + public void run() { + brokerStatsManager.getMomentStatsItemSetFallTime().setValue("test",10); + } + }); + } + while (true) { + if (executor.getCompletedTaskCount() == 10000) { + break; + } + Thread.sleep(1000); + } + return brokerStatsManager.getMomentStatsItemSetFallTime().getAndCreateStatsItem("test").getValue(); + } + @After public void shutdown() { executor.shutdown(); diff --git a/common/src/main/java/org/apache/rocketmq/common/stats/MomentStatsItemSet.java b/common/src/main/java/org/apache/rocketmq/common/stats/MomentStatsItemSet.java index d3b5596611e6d1fe196ec1821d1c7720eee7e9cd..a38b53ffd537bd6462278773124c8b5f82d4e818 100644 --- a/common/src/main/java/org/apache/rocketmq/common/stats/MomentStatsItemSet.java +++ b/common/src/main/java/org/apache/rocketmq/common/stats/MomentStatsItemSet.java @@ -79,10 +79,10 @@ public class MomentStatsItemSet { if (null == statsItem) { statsItem = new MomentStatsItem(this.statsName, statsKey, this.scheduledExecutorService, this.log); - MomentStatsItem prev = this.statsItemTable.put(statsKey, statsItem); - - if (null == prev) { + MomentStatsItem prev = this.statsItemTable.putIfAbsent(statsKey, statsItem); + if (null != prev) { + statsItem = prev; // statsItem.init(); } }