Skip to content

Commit cd634d8

Browse files
committed
Cache event classes
The DefaultEventService looks up the SciJavaEvent class for each Method to verify the method is a valid EventHandler. As the class associated with a given method does not change over time, it is reasonable to cache the result.
1 parent 6ef0392 commit cd634d8

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

src/main/java/org/scijava/event/DefaultEventService.java

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,10 @@
3535
import java.lang.reflect.Method;
3636
import java.util.ArrayList;
3737
import java.util.Collection;
38+
import java.util.HashMap;
3839
import java.util.HashSet;
3940
import java.util.List;
41+
import java.util.Map;
4042
import java.util.WeakHashMap;
4143

4244
import org.bushe.swing.event.annotation.AbstractProxySubscriber;
@@ -80,6 +82,12 @@ public class DefaultEventService extends AbstractService implements
8082

8183
private DefaultEventBus eventBus;
8284

85+
/**
86+
* A cache for mapping {@link Method}s to the {@link SciJavaEvent} class taken
87+
* as parameters. Only methods with event parameters will cached here.
88+
*/
89+
private final Map<Method, Class<?>> eventClasses = new HashMap<Method, Class<?>>();
90+
8391
/**
8492
* Set of claimed {@link EventHandler#key()}s. Additional event handlers
8593
* specifying the same key will be ignored rather than subscribed.
@@ -198,14 +206,24 @@ private <E extends SciJavaEvent> EventSubscriber<E> subscribe(
198206

199207
/** Gets the event class parameter of the given method. */
200208
private Class<? extends SciJavaEvent> getEventClass(final Method m) {
201-
final Class<?>[] c = m.getParameterTypes();
202-
if (c == null || c.length != 1) return null; // wrong number of args
203-
if (!SciJavaEvent.class.isAssignableFrom(c[0])) return null; // wrong class
209+
// Check for a cached entry for the given method
210+
Class<?> eventClass = eventClasses.get(m);
211+
212+
if (eventClass == null) {
213+
final Class<?>[] c = m.getParameterTypes();
214+
if (c == null || c.length != 1) return null; // wrong number of args
215+
if (!SciJavaEvent.class.isAssignableFrom(c[0])) return null; // wrong class
216+
217+
// Cache the eventClass
218+
eventClass = c[0];
219+
eventClasses.put(m, eventClass);
220+
}
204221

205222
@SuppressWarnings("unchecked")
206-
final Class<? extends SciJavaEvent> eventClass =
207-
(Class<? extends SciJavaEvent>) c[0];
208-
return eventClass;
223+
final Class<? extends SciJavaEvent> typedClass =
224+
(Class<? extends SciJavaEvent>) eventClass;
225+
226+
return typedClass;
209227
}
210228

211229
// -- Event handlers garbage collection preventer --

0 commit comments

Comments
 (0)