0

How to modify that class:

public class Event<T extends EventArgs> {
    private final List<Listener<T>> listeners;

    public Event() {
        listeners = new ArrayList<>();
    }

    public void invoke(T args) {
        for (Listener<T> l : listeners)
                    l.onEvent(args);
    }

    public void addEventListener(Listener<T> l) {
        listeners.add(l);
    }


    public void removeEventListener(Listener<T> l) {
        listeners.remove(l);
    }
}

So addEventListener() and removeEventListener() will be postponed to execute after invoke() ends (so I won't get ConcurrentModificationException)?

zduny
  • 2,481
  • 1
  • 27
  • 49

1 Answers1

0

Depending on how long you expect invoke() to run you have two choices. If its execution is always less than a short interval (i.e. 10ms) then you could just lock on the class. Otherwise you need to queue up the operations and have the invoke method run them in sequence after it's done.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190