Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ISSUE #309] Fix addConnectionEventProcessor concurrency problems #312

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions src/main/java/com/alipay/remoting/ConnectionEventListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -27,7 +28,9 @@
*/
public class ConnectionEventListener {

private ConcurrentHashMap<ConnectionEventType, List<ConnectionEventProcessor>> processors = new ConcurrentHashMap<ConnectionEventType, List<ConnectionEventProcessor>>(
private final ReentrantLock lock = new ReentrantLock();

private final ConcurrentHashMap<ConnectionEventType, List<ConnectionEventProcessor>> processors = new ConcurrentHashMap<ConnectionEventType, List<ConnectionEventProcessor>>(
3);

/**
Expand All @@ -54,12 +57,16 @@ public void onEvent(ConnectionEventType type, String remoteAddress, Connection c
*/
public void addConnectionEventProcessor(ConnectionEventType type,
ConnectionEventProcessor processor) {
List<ConnectionEventProcessor> processorList = this.processors.get(type);
if (processorList == null) {
this.processors.putIfAbsent(type, new ArrayList<ConnectionEventProcessor>(1));
processorList = this.processors.get(type);
lock.lock();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As mentioned in #309, it is ArrayList not thread safe. I think it is better to replace ArrayList to a thread safe List implementation such as CopyOnWriteArrayList instead of using a lock.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@zjcscut will you adjust it based on the above suggestions?

try {
List<ConnectionEventProcessor> processorList = this.processors.get(type);
if (null == processorList) {
processorList = new ArrayList<ConnectionEventProcessor>(1);
this.processors.put(type, processorList);
}
processorList.add(processor);
} finally {
lock.unlock();
}
processorList.add(processor);
}

}