1919import org .slf4j .Logger ;
2020import org .slf4j .LoggerFactory ;
2121
22+ import java .util .Collections ;
2223import java .util .LinkedHashMap ;
2324import java .util .Map ;
2425import java .util .concurrent .atomic .AtomicInteger ;
@@ -33,7 +34,7 @@ public class NotificationManager<T> {
3334
3435 private static final Logger logger = LoggerFactory .getLogger (NotificationManager .class );
3536
36- private final Map <Integer , NotificationHandler <T >> handlers = new LinkedHashMap <>();
37+ private final Map <Integer , NotificationHandler <T >> handlers = Collections . synchronizedMap ( new LinkedHashMap <>() );
3738 private final AtomicInteger counter ;
3839
3940 public NotificationManager () {
@@ -47,10 +48,12 @@ public NotificationManager(AtomicInteger counter) {
4748 public int addHandler (NotificationHandler <T > newHandler ) {
4849
4950 // 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+ }
5457 }
5558 }
5659
@@ -61,11 +64,13 @@ public int addHandler(NotificationHandler<T> newHandler) {
6164 }
6265
6366 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+ }
6974 }
7075 }
7176 }
0 commit comments