19
19
import org .slf4j .Logger ;
20
20
import org .slf4j .LoggerFactory ;
21
21
22
+ import java .util .Collections ;
22
23
import java .util .LinkedHashMap ;
23
24
import java .util .Map ;
24
25
import java .util .concurrent .atomic .AtomicInteger ;
@@ -33,7 +34,7 @@ public class NotificationManager<T> {
33
34
34
35
private static final Logger logger = LoggerFactory .getLogger (NotificationManager .class );
35
36
36
- private final Map <Integer , NotificationHandler <T >> handlers = new LinkedHashMap <>();
37
+ private final Map <Integer , NotificationHandler <T >> handlers = Collections . synchronizedMap ( new LinkedHashMap <>() );
37
38
private final AtomicInteger counter ;
38
39
39
40
public NotificationManager () {
@@ -47,10 +48,12 @@ public NotificationManager(AtomicInteger counter) {
47
48
public int addHandler (NotificationHandler <T > newHandler ) {
48
49
49
50
// Prevent registering a duplicate listener.
50
- for (NotificationHandler <T > handler : handlers .values ()) {
51
- if (handler .equals (newHandler )) {
52
- logger .warn ("Notification listener was already added" );
53
- return -1 ;
51
+ synchronized (handlers ) {
52
+ for (NotificationHandler <T > handler : handlers .values ()) {
53
+ if (handler .equals (newHandler )) {
54
+ logger .warn ("Notification listener was already added" );
55
+ return -1 ;
56
+ }
54
57
}
55
58
}
56
59
@@ -61,11 +64,13 @@ public int addHandler(NotificationHandler<T> newHandler) {
61
64
}
62
65
63
66
public void send (final T message ) {
64
- for (Map .Entry <Integer , NotificationHandler <T >> handler : handlers .entrySet ()) {
65
- try {
66
- handler .getValue ().handle (message );
67
- } catch (Exception e ) {
68
- logger .warn ("Catching exception sending notification for class: {}, handler: {}" , message .getClass (), handler .getKey ());
67
+ synchronized (handlers ) {
68
+ for (Map .Entry <Integer , NotificationHandler <T >> handler : handlers .entrySet ()) {
69
+ try {
70
+ handler .getValue ().handle (message );
71
+ } catch (Exception e ) {
72
+ logger .warn ("Catching exception sending notification for class: {}, handler: {}" , message .getClass (), handler .getKey ());
73
+ }
69
74
}
70
75
}
71
76
}
0 commit comments