Search code examples
javaobserver-pattern

How to store Listeners for multiple Event types


I'm trying to implement Observer/Listener pattern with multiple listeners and multiple event types in Java. Each event listener can be interested in one or more event types.

What is the most efficient way to store listeners for each particular event type and iterate over them (List of Lists, maybe)?

Of course, thread-safe solution is strongly preferred.


Solution

  • You can use java.util.concurrent.ConcurrentHashMap for Thread safe hash map.

    The structure you need is:

    ConcurrentHashMap<EventType,List<Listener>> map;
    

    That way, each listener is registered to several event types.