EventBus icon indicating copy to clipboard operation
EventBus copied to clipboard

Use a delegate object for `MonitorAware` events

Open Jonathing opened this issue 9 months ago • 2 comments

The way the experimental MonitorAware characteristic works is that it is tied to the MutableEvent object, whose internals have tracking for the monitoring state. This allows the same event object to be passed into the listener for that event.

An idea that I have to solve needing to tie monitor-awareness to MutableEvent is to instead prompt the event to return an instance of the event that would be used for monitoring listeners. For record events, this would just be themselves since they are immutable. But for inheritable events, it would be possible to return a subtype of the event where setters throw exceptions and getters for collections return unmodifiable views. While this would be more expensive than the system currently in place, it would be far more versatile, additionally removing the limitation of needing it to strictly be a subtype of MutableEvent.

Jonathing avatar Apr 24 '25 02:04 Jonathing

A delegate system sounds like a good idea, although it comes at the cost of verbosity and an extra allocation per post when there are monitoring listeners present on the event's associated bus.

The verbosity would come from needing three separate types - the event interface which implements InheritableEvent, the record which holds the actual data and an unmodifiable view record, along with duplicated methods for each mutator you want to guard against and each accessor to delegate to. Note that records are shallowly immutable and are final classes, so having a record return itself may not always be an option (e.g. if it contains a mutable list as a record component).

By using MutableEvent for this, it's all in one place. You call isMonitoring() within each mutator method you want to guard against and that's all. With JDK-8349536 JEP draft: Prepare to Make Final Mean Final on the horizon, there will be less of a need to use records in the cases where you're mainly doing them for performance reasons.

The experimental features are something I'd like to revisit in a future release after EventBus 7 is integrated into Forge. Your idea has merit, but I'm not sure how long it would be useful for when considering the linked JEP and verbosity compromises.

PaintNinja avatar Apr 24 '25 10:04 PaintNinja

If we want to keep future Java in mind, that is fine. But the way monitor-aware events currently working is rather awkward.

Jonathing avatar Apr 25 '25 14:04 Jonathing