FIUS / ICGE

Introduction Course Game Engine for the FIUS Java Introduction Course
MIT License
3 stars 2 forks source link

treewide: Introduced the so-called `EventHandler`s #86

Closed haslersn closed 5 years ago

haslersn commented 6 years ago

TL;DR

Events are now handled by adding an EventListener to an EventHandler which gets registered to the EventDispatcher. The EventHandlers are only weakly referenced inside the EventDispatcher.

What changed

Previously events were handled by registering an EventListener to the EventDispatcher. Now events are handled by creating an EventHandler, registering that EventHandler to the EventDispatcher and then registering an EventListener to the EventHandler. EventDispatcher is still a singleton. There can be arbitrarily man EventHandlers added to the EventDispatcher and arbitrarily many EventListeners added to one EventHandler.

The important thing:

EventHandlers are only weakly-referenced by the EventDispatcher. The code that registers them have to keep a reference to the EventHandler in order to prevent them from being garbage collected.

Why:

EventListeners often keep references to objects. That way, if the EventListener isn't eventually removed from the EventDispatcher it stays alive forever together with all of the objects if references directly or indirectly, thus leaking memory. (Leaking memory here means that memory isn't freed even though it's not needed anymore. This differs from the C-meaning of a memory leak where the memory can't be referenced anymore. The memory can still theoretically be referenced, but isn't by the program.)

Now the calling code can (and must keep a reference to the EventHandler inside some object to which that EventHandler is meaningfully associated. If that object gets garbage collected, there won't be any strong reference to the EventHandler anymore (since it's only weakly referenced by the EventDispatcher, using a WeakReference<EventHandler>) and the EventHandler will therefore be garbage collected as well.