From 5197e9a26f00ac4158823eb4fab7e1d34765d4b3 Mon Sep 17 00:00:00 2001 From: Throwable <739805340@qq.com> Date: Thu, 3 Nov 2022 22:50:26 +0800 Subject: [PATCH] fix addConnectionEventProcessor concurrency problems --- .../remoting/ConnectionEventListener.java | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/alipay/remoting/ConnectionEventListener.java b/src/main/java/com/alipay/remoting/ConnectionEventListener.java index f91ca1ad..ddd93c17 100644 --- a/src/main/java/com/alipay/remoting/ConnectionEventListener.java +++ b/src/main/java/com/alipay/remoting/ConnectionEventListener.java @@ -19,6 +19,7 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReentrantLock; /** * Listen and dispatch connection events. @@ -27,7 +28,9 @@ */ public class ConnectionEventListener { - private ConcurrentHashMap> processors = new ConcurrentHashMap>( + private final ReentrantLock lock = new ReentrantLock(); + + private final ConcurrentHashMap> processors = new ConcurrentHashMap>( 3); /** @@ -54,12 +57,16 @@ public void onEvent(ConnectionEventType type, String remoteAddress, Connection c */ public void addConnectionEventProcessor(ConnectionEventType type, ConnectionEventProcessor processor) { - List processorList = this.processors.get(type); - if (processorList == null) { - this.processors.putIfAbsent(type, new ArrayList(1)); - processorList = this.processors.get(type); + lock.lock(); + try { + List processorList = this.processors.get(type); + if (null == processorList) { + processorList = new ArrayList(1); + this.processors.put(type, processorList); + } + processorList.add(processor); + } finally { + lock.unlock(); } - processorList.add(processor); } - }