API REVIEW: Weak event handler

Lubomir Nerad lubomir.nerad at oracle.com
Wed Jun 13 06:32:26 PDT 2012

Hi John,

the usage of weak version of EventHandler and 
(Invalidation|Change)Listener will be very similar. With the current 
proposal they will differ only in the way they are created (constructor 
vs. factory method). And I think that the adoption of factory method 
would be beneficial also for the Weak*Listener-s.

But you are right that we should try to align them more closely from the 
implementation point of view and from the way they will be identified 
and handled by their respective containers.


On 6/13/2012 5:59 AM, John Hendrikx wrote:
> This seems to be significantly different from how 
> WeakInvalidationListener and WeakChangeListener are implemented, 
> should they not be the same?
> On 12/06/2012 13:47, Lubomir Nerad wrote:
>> 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