API REVIEW: Weak event handler

Lubomir Nerad lubomir.nerad at oracle.com
Wed Jun 13 08:49:52 PDT 2012


Hi Jonathan,

On 6/12/2012 9:46 PM, Jonathan Giles wrote:
> For what it is worth, the UI controls team have a WeakEventHandler 
> class in com.sun.javafx.scene.control. It does not follow quite the 
> same direction as you have outlined, but you may find it interesting 
> nonetheless. It would be good to remove our implementation once the 
> public API becomes available, but I can't imagine you'd be adding the 
> WeakEventHandler as a feature into 2.2 now, would you?
>

You are right, this is for 3.0.

> -- Jonathan
>

Thanks,
Lubo

>
> On 12/06/2012 11:47 p.m., 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