Skip to content

Commit f0d1dd1

Browse files
ctruedenclaude
andcommitted
scijava-context: @eventhandler scanning
The container turns annotated methods into subscriptions, which is what the two-tier design was protecting: the event bus itself stays reflection-free and needs no `opens` from anyone using it directly, while the container -- which already reflects, for injection -- provides the convenience. A service's handlers are subscribed when the context creates it and dropped when the context is disposed. A service's lifetime being the context's, the author writes no subscription or cleanup code at all, and needs no `opens` beyond the one @dependency already requires. Objects the context did not create are not subscribed automatically. A plugin may be created and discarded many times in a session, and handlers outliving their objects would pile up -- the leak that weak references used to paper over. Context.subscribe(Object) returns the subscriptions for the caller to close. What a handler throws reaches the publisher unwrapped rather than as an InvocationTargetException, so the event bus's aggregated failures say something useful. scijava-context-test covers the case that matters: a service with a private handler, in a package opened only to the container, hearing events and falling silent when the context is disposed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gJpzGd3ksbME4CN6Tu2ni
1 parent 8c48289 commit f0d1dd1

10 files changed

Lines changed: 506 additions & 3 deletions

File tree

‎docs/migration-plan.md‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -559,8 +559,20 @@ No application context required by anything in this phase.
559559
real module boundary, proving both halves of the earlier claim at once:
560560
the qualified `opens` grants the container deep reflection, and the
561561
package is still exported to nobody.
562-
- Still to do here: `@EventHandler` scanning, the one-way legacy bridge, and
563-
the core services themselves.
562+
- **`@EventHandler` scanning is done**, and it is what the two-tier design
563+
was protecting: the event bus itself stays reflection-free, while the
564+
container — which already reflects — turns annotated methods into
565+
subscriptions. A service's handlers are subscribed when the context
566+
creates it and dropped when the context is disposed, so a service author
567+
writes no subscription or cleanup code at all.
568+
- Objects the context did **not** create are not subscribed automatically:
569+
a plugin may be created and discarded many times in a session, and
570+
handlers outliving their objects would pile up. `Context.subscribe(Object)`
571+
returns the subscriptions for the caller to close.
572+
- What a handler throws reaches the publisher unwrapped, rather than as an
573+
`InvocationTargetException`.
574+
- Still to do here: the one-way legacy bridge, and the core services
575+
themselves.
564576
- **Dependencies are not constructor arguments.** Constructor injection
565577
would publish every dependency in a signature, so changing an internal
566578
dependency would be an API change and a binary compatibility break unless

‎docs/migration.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ A **dropped** row is a successful outcome, not a gap.
104104
| `io.nio.ByteBufferByteBank` | `org.scijava.io3.ByteBufferByteBank`, with `direct()` factories and an `isDirect()` accessor. Off-heap direct buffers are its reason to exist alongside `ByteArrayByteBank`: bytes reach native code and shared memory without a copy, which matters increasingly for Appose's named shared memory blocks. **Bug fixed in the port:** growing a direct bank reallocated with `ByteBuffer.allocate`, quietly moving the bytes back onto the heap; it now grows through the bank's own provider | ported |
105105
| `io.nio.NIOService` | **not ported** — it wraps two JDK calls behind a system-property switch, was inherited from old Bio-Formats code, and SCIFIO only exposes it as a gateway accessor (`SCIFIO.nio()`) without using it. Nothing in the ported architecture precludes `FileChannel`-based handles later: a handle is free to open a channel, and a byte bank is free to be backed by a mapped buffer | dropped |
106106
| `io` (`IOPlugin`, `IOService`, `RecentFileService`) | `scijava-io3` (Phase 1), pending review of what is still used | open |
107+
| `event.EventHandler` | `org.scijava.context.EventHandler`, scanned by the container rather than the bus: a service's handlers are subscribed on creation and dropped on context dispose. The bus itself stays reflection-free | ported |
107108
| `event`, `event.bushe` | `org.scijava.events`, a clean-room rewrite. `EventService` becomes `EventBus`, one per context and with no shared instance. `subscribe` takes a lambda rather than scanning `@EventHandler` methods, and returns a `Subscription`; subscribers are held strongly and dropped by `EventBus.close()`. Events need no `SciJavaEvent` base type. Consumption is opt-in via `Consumable`; subscriber order is by `scijava-priority` | ported |
108109
| `event.EventHistory`, `DefaultEventHistory` | dropped — a subscriber on `Object.class` reproduces it. The macro-recorder need behind it deserves an explicit layer | dropped |
109110
| `parse` | Parsington (`org.scijava.parsington`) | planned |

‎scijava-context-test/src/main/java/module-info.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
requires org.scijava.discovery;
4040

4141
provides org.scijava.context.Service with
42-
org.scijava.context.test.impl.HiddenGreeter;
42+
org.scijava.context.test.impl.HiddenGreeter,
43+
org.scijava.context.test.impl.DefaultRecordingService;
4344

4445
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*-
2+
* #%L
3+
* Integration tests for the scijava-context library.
4+
* %%
5+
* Copyright (C) 2021 - 2025 SciJava developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.context.test;
31+
32+
import java.util.List;
33+
34+
import org.scijava.context.Service;
35+
36+
/** A service that records the shouts it hears. */
37+
public interface RecordingService extends Service {
38+
39+
List<String> recorded();
40+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*-
2+
* #%L
3+
* Integration tests for the scijava-context library.
4+
* %%
5+
* Copyright (C) 2021 - 2025 SciJava developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.context.test;
31+
32+
/** An event, needing no base type. */
33+
public class ShoutRecorded {
34+
35+
private final String text;
36+
37+
public ShoutRecorded(final String text) {
38+
this.text = text;
39+
}
40+
41+
public String text() {
42+
return text;
43+
}
44+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*-
2+
* #%L
3+
* Integration tests for the scijava-context library.
4+
* %%
5+
* Copyright (C) 2021 - 2025 SciJava developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.context.test.impl;
31+
32+
import java.util.ArrayList;
33+
import java.util.List;
34+
35+
import org.scijava.context.EventHandler;
36+
import org.scijava.context.test.RecordingService;
37+
import org.scijava.context.test.ShoutRecorded;
38+
39+
/**
40+
* A service whose event handler is <em>private</em>, in a package opened only
41+
* to the container.
42+
*/
43+
public class DefaultRecordingService implements RecordingService {
44+
45+
private final List<String> recorded = new ArrayList<>();
46+
47+
@EventHandler
48+
private void onShout(final ShoutRecorded event) {
49+
recorded.add(event.text());
50+
}
51+
52+
@Override
53+
public List<String> recorded() {
54+
return recorded;
55+
}
56+
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*-
2+
* #%L
3+
* Integration tests for the scijava-context library.
4+
* %%
5+
* Copyright (C) 2021 - 2025 SciJava developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.context.test;
31+
32+
import static org.junit.jupiter.api.Assertions.assertEquals;
33+
import static org.junit.jupiter.api.Assertions.assertTrue;
34+
35+
import java.util.List;
36+
37+
import org.junit.jupiter.api.Test;
38+
import org.scijava.context.Context;
39+
40+
/**
41+
* Tests that a service's {@code @EventHandler} methods are subscribed for it,
42+
* across a real module boundary and with the handler private.
43+
*
44+
* @author Curtis Rueden
45+
*/
46+
public class EventHandlerTest {
47+
48+
/**
49+
* The convenience that matters: a service author annotates a method and
50+
* writes no subscription or cleanup code at all.
51+
*/
52+
@Test
53+
public void testServiceHandlerNeedsNoCleanupCode() {
54+
final Context context = Context.create();
55+
final RecordingService recorder = context.service(RecordingService.class);
56+
57+
context.events().publish(new ShoutRecorded("one"));
58+
context.events().publish(new ShoutRecorded("two"));
59+
assertEquals(List.of("one", "two"), recorder.recorded());
60+
61+
// Disposing the context ends the subscription; the author wrote nothing.
62+
context.dispose();
63+
context.events().publish(new ShoutRecorded("three"));
64+
assertEquals(List.of("one", "two"), recorder.recorded());
65+
}
66+
67+
/** Subscribing a private method needs no export, only the container's opens. */
68+
@Test
69+
public void testHandlersStayEncapsulated() {
70+
try (final Context context = Context.create()) {
71+
context.service(RecordingService.class);
72+
final Module module = RecordingService.class.getModule();
73+
assertTrue(module.isNamed(), "not running on the module path");
74+
assertTrue(module.isOpen("org.scijava.context.test.impl", //
75+
Context.class.getModule()));
76+
assertTrue(!module.isExported("org.scijava.context.test.impl"));
77+
}
78+
}
79+
}

‎scijava-context/src/main/java/org/scijava/context/Context.java‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@
3030
package org.scijava.context;
3131

3232
import java.lang.reflect.Field;
33+
import java.lang.reflect.InvocationTargetException;
34+
import java.lang.reflect.Method;
3335
import java.util.ArrayList;
3436
import java.util.Collections;
3537
import java.util.Comparator;
@@ -45,6 +47,7 @@
4547

4648
import org.scijava.discovery.Discovery;
4749
import org.scijava.events.EventBus;
50+
import org.scijava.events.Subscription;
4851
import org.scijava.index.IndexDiscoverer;
4952
import org.scijava.spi.Disposable;
5053

@@ -156,6 +159,9 @@ public <S extends Service> Optional<S> optionalService(final Class<S> type) {
156159
// on each other resolve instead of recursing.
157160
byRequestedType.put(type, s);
158161
inject(s);
162+
// NB: a service's lifetime is the context's, so its handlers need
163+
// no cleanup by the author: disposing the context closes the bus.
164+
subscribe(s);
159165
initialize(s);
160166
// NB: record for disposal only once initialization has finished.
161167
// A service's dependencies finish first, so they land earlier in
@@ -219,6 +225,34 @@ public void inject(final Object target) {
219225
}
220226
}
221227

228+
/**
229+
* Subscribes the {@link EventHandler}-annotated methods of the given object
230+
* to this context's {@link EventBus}.
231+
* <p>
232+
* Services are subscribed automatically when the context creates them, and
233+
* unsubscribed when it is disposed. This is for everything else: a plugin
234+
* may be created and discarded many times in a session, so its handlers are
235+
* the caller's to manage.
236+
* </p>
237+
*
238+
* @param target the object whose handlers to subscribe
239+
* @return a subscription per handler; close them when the object is done
240+
* @throws ServiceException if a handler is malformed, or the target's
241+
* package is not open to this module
242+
*/
243+
public List<Subscription> subscribe(final Object target) {
244+
if (target == null) throw new NullPointerException("target");
245+
final List<Subscription> subscriptions = new ArrayList<>();
246+
for (Class<?> c = target.getClass(); c != null; c = c.getSuperclass()) {
247+
for (final Method method : c.getDeclaredMethods()) {
248+
final EventHandler handler = method.getAnnotation(EventHandler.class);
249+
if (handler == null) continue;
250+
subscriptions.add(subscribeHandler(target, method, handler));
251+
}
252+
}
253+
return subscriptions;
254+
}
255+
222256
/** Gets this context's event bus. */
223257
public EventBus events() {
224258
return events;
@@ -310,6 +344,54 @@ private void injectField(final Object target, final Field field,
310344
}
311345
}
312346

347+
/** Subscribes one annotated method. */
348+
private Subscription subscribeHandler(final Object target,
349+
final Method method, final EventHandler handler)
350+
{
351+
final Class<?>[] params = method.getParameterTypes();
352+
if (params.length != 1) {
353+
throw new ServiceException("An @EventHandler takes exactly one" + //
354+
" parameter, the event: " + method.getDeclaringClass().getName() + //
355+
"." + method.getName() + " takes " + params.length);
356+
}
357+
try {
358+
// NB: the same deep reflection, and the same `opens`, that
359+
// @Dependency needs.
360+
method.setAccessible(true);
361+
}
362+
catch (final RuntimeException exc) {
363+
throw new ServiceException("Cannot subscribe " + method
364+
.getDeclaringClass().getName() + "." + method.getName() + //
365+
". Does its module declare `opens " + method.getDeclaringClass()
366+
.getPackageName() + " to org.scijava.context;`?", exc);
367+
}
368+
return subscribeTyped(params[0], handler.priority(), target, method);
369+
}
370+
371+
/** Captures the event type, so that the bus sees a typed subscription. */
372+
private <E> Subscription subscribeTyped(final Class<E> eventType,
373+
final double priority, final Object target, final Method method)
374+
{
375+
return events.subscribe(eventType, priority, event -> {
376+
try {
377+
method.invoke(target, event);
378+
}
379+
catch (final IllegalAccessException exc) {
380+
throw new ServiceException("Cannot invoke handler " + method
381+
.getDeclaringClass().getName() + "." + method.getName(), exc);
382+
}
383+
catch (final InvocationTargetException exc) {
384+
// NB: unwrap, so subscribers see what the handler actually threw
385+
// rather than a reflection wrapper.
386+
final Throwable cause = exc.getCause();
387+
if (cause instanceof RuntimeException) throw (RuntimeException) cause;
388+
if (cause instanceof Error) throw (Error) cause;
389+
throw new ServiceException("Handler failed: " + method
390+
.getDeclaringClass().getName() + "." + method.getName(), cause);
391+
}
392+
});
393+
}
394+
313395
/** Resolves what to inject for a field of the given type. */
314396
private Object resolve(final Class<?> type) {
315397
if (type == Context.class) return this;

0 commit comments

Comments
 (0)