API REVIEW: Weak event handler

Lubomir Nerad lubomir.nerad at oracle.com
Tue Jun 12 04:47:35 PDT 2012


Hi All,

there is a request to add a WeakEventHandler to the API 
(http://javafx-jira.kenai.com/browse/RT-13706). This will be a simple 
wrapper for the target event handler to which it will delegate the 
handle calls. It will reference the target weakly and so it won't 
prevent it from being garbage collected.

My proposal for this class is:

package javafx.event;

public final class WeakEventHandler<T extends Event>
         extends WeakReference<EventHandler<T>>
         implements EventHandler<T> {

     private WeakEventHandler(EventHandler<T> eventHandler) { ... }

     @Override public void handle(final T event) { ... }

     public static <T extends Event> WeakEventHandler<T> 
create(EventHandler<T> eventHandler) { ... }
}

I decided to make this class both an EventHandler (implements) and a 
WeakReference (extends). Mainly I needed to have some way how to test 
from event handler containers whether the target event handler for a 
stored wrapper has been garbage collected and so the wrapper can be 
removed as well. Extending WeakReference adds the required method 
(WeakReference.get()) and saves some object instances. It also brings 
the clear method, which can simplify testing of this feature.

WeakEventHandler instances will be created through the create factory 
method. This is to avoid repetition of the event type during event 
handler registration.

So instead of:
node.setOnMousePressed(new WeakEventHandler<MouseEvent>(new 
EventHandler<MouseEvent>() { ... }));

we can use:
node.setOnMousePressed(WeakEventHandler.create(new 
EventHandler<MouseEvent>() { ... }));

I also considered to define the WeakEventHandler as an interface which 
extends EventHandler, but adds no additional methods. Then leave it to 
event handler containers to reference such event handlers weakly. This 
has very simple and direct usage, but also its own problems. We can 
discuss it further if you find this solution preferred to the wrapper 
approach.

Thanks,
Lubo



More information about the openjfx-dev mailing list