Skip to content

Commit a915112

Browse files
committed
Added async events
1 parent 77f3880 commit a915112

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

src/main/java/at/jkvn/eventlib/EventLib.java

+23-3
Original file line numberDiff line numberDiff line change
@@ -18,27 +18,43 @@
1818
import java.util.Arrays;
1919
import java.util.Comparator;
2020
import java.util.List;
21+
import java.util.concurrent.ExecutorService;
22+
import java.util.concurrent.Executors;
2123

2224
@Getter
2325
public class EventLib {
2426
@Getter
2527
private static Configuration configuration;
2628
@Getter
2729
private static final List<Listener> listeners = new ArrayList<>();
30+
@Getter
31+
private static final ExecutorService executor = Executors.newCachedThreadPool();
2832

2933
@SneakyThrows
3034
public static void call(Event event) {
3135
if (isAutomatic()) {
32-
invokeMethods(getMethods(), event);
36+
invokeMethods(getMethods(), event, false);
37+
return;
38+
}
39+
40+
(new ArrayList<>(listeners)).forEach(listener -> {
41+
invokeMethods(Arrays.stream(listener.getClass().getMethods()).toList(), event, false);
42+
});
43+
}
44+
45+
@SneakyThrows
46+
public static void callAsync(Event event) {
47+
if (isAutomatic()) {
48+
invokeMethods(getMethods(), event, true);
3349
return;
3450
}
3551

3652
(new ArrayList<>(listeners)).forEach(listener -> {
37-
invokeMethods(Arrays.stream(listener.getClass().getMethods()).toList(), event);
53+
invokeMethods(Arrays.stream(listener.getClass().getMethods()).toList(), event, true);
3854
});
3955
}
4056

41-
private static void invokeMethods(List<Method> methods, Event event) {
57+
private static void invokeMethods(List<Method> methods, Event event, boolean async) {
4258
methods.stream()
4359
.filter(method -> method.getParameterCount() == 1
4460
&& method.getParameterTypes()[0].isAssignableFrom(event.getClass()))
@@ -47,6 +63,10 @@ private static void invokeMethods(List<Method> methods, Event event) {
4763
return priority != null ? priority.value().ordinal() : EventPriority.NORMAL.ordinal();
4864
}))
4965
.forEach(method -> {
66+
if (async) {
67+
executor.execute(() -> invokeSafely(method, event));
68+
return;
69+
}
5070
invokeSafely(method, event);
5171
});
5272
}

src/test/java/TestProject.java

+9
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,15 @@ public void call() {
5151
assertTrue(dummyEvent.wasCalled());
5252
}
5353

54+
@Test
55+
public void callAsync() {
56+
DummyEvent dummyEvent = new DummyEvent();
57+
58+
EventLib.callAsync(dummyEvent);
59+
60+
assertTrue(dummyEvent.wasCalled());
61+
}
62+
5463
@EventHandler
5564
public void onDummyEvent(DummyEvent event) {
5665
event.call();

0 commit comments

Comments
 (0)