Introduce event-driven API, modular threading, and enhanced server lifecycle tools
Add `Events` and `EventBus` for mod-driven event handling with support for main-thread and mod-thread execution. Introduce `MainThread` and `AsyncExecutor` for modular threading and background task management. Add `ForgeSettings` to manage global mod configuration through `forge.toml`. Include tests for events, threading, and configuration parsing to improve robustness and maintainability.
This commit is contained in:
1 parent
3b21fc3aa6
commit
a0d1ec2feb
30 files changed
+1683
-19
No files matched your search
@@ -1,5 +1,6 @@
|
||||
package dev.overlord.zomboidforge.core;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Event;
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.core.mods.ModLoadException;
|
||||
import dev.overlord.zomboidforge.core.mods.ModVersion;
|
||||
@@ -12,6 +13,7 @@ import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import testmods.ContextMod;
|
||||
import testmods.Recorder;
|
||||
import testmods.ThreadMod;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
@@ -20,6 +22,7 @@ import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -220,4 +223,48 @@ class ForgeTest
|
||||
}
|
||||
|
||||
private static Object field(Object mod, String name) throws ReflectiveOperationException { return mod.getClass().getField(name).get(mod); }
|
||||
|
||||
@Test
|
||||
void modsUseTheirThreadTheMainThreadAndEvents() throws Exception
|
||||
{
|
||||
TestMods.folder(this.mods, "threads", TestMods.toml("threads", ThreadMod.class.getName(), ""), Map.of(
|
||||
"testmods/ThreadMod", TestMods.classFile(ThreadMod.class),
|
||||
"testmods/ThreadMod$Greeting", TestMods.classFile(ThreadMod.Greeting.class)
|
||||
));
|
||||
|
||||
Forge forge = this.load();
|
||||
Object mod = forge.mods().getFirst().mod();
|
||||
String main = Thread.currentThread().getName();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> log = (List<String>) ForgeTest.field(mod, "log");
|
||||
|
||||
forge.started();
|
||||
ForgeTest.await(() -> log.contains("work on zf-mod-threads"));
|
||||
assertEquals(List.of("work on zf-mod-threads"), log, "the hand-off to main waits for the tick");
|
||||
|
||||
forge.tick();
|
||||
assertEquals(1L, ForgeTest.field(mod, "ticks"));
|
||||
assertEquals("result on " + main, log.getLast());
|
||||
|
||||
// The listener is registered for the Greeting class of the mod's own class loader.
|
||||
Class<?> greeting = mod.getClass().getClassLoader().loadClass(ThreadMod.Greeting.class.getName());
|
||||
forge.post((Event) greeting.getConstructor(String.class).newInstance("hi"));
|
||||
ForgeTest.await(() -> log.contains("greeting hi on zf-mod-threads"));
|
||||
|
||||
forge.stopping();
|
||||
assertEquals("stopping", log.getLast());
|
||||
assertEquals(Lifecycle.Phase.STOPPING, forge.phase());
|
||||
}
|
||||
|
||||
private static void await(BooleanSupplier condition) throws InterruptedException
|
||||
{
|
||||
long deadline = System.nanoTime() + 5_000_000_000L;
|
||||
|
||||
while (!condition.getAsBoolean())
|
||||
{
|
||||
if (System.nanoTime() > deadline) throw new AssertionError("Condition not met within 5 s.");
|
||||
Thread.sleep(10);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package dev.overlord.zomboidforge.core;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
/** {@link System.Logger} that keeps every message as {@code "LEVEL: message"}, with {@code " (<exception>)"} when one is given. */
|
||||
public final class RecordingLogger implements System.Logger
|
||||
{
|
||||
public final List<String> messages = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
@Override
|
||||
public String getName() { return "test"; }
|
||||
|
||||
@Override
|
||||
public boolean isLoggable(Level level) { return true; }
|
||||
|
||||
@Override
|
||||
public void log(Level level, @Nullable ResourceBundle bundle, @Nullable String message, @Nullable Throwable thrown)
|
||||
{
|
||||
this.messages.add(level.getName() + ": " + message + (thrown == null ? "" : " (" + thrown + ")"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void log(Level level, @Nullable ResourceBundle bundle, @Nullable String format, @Nullable Object @Nullable ... parameters)
|
||||
{
|
||||
this.log(level, bundle, format == null || parameters == null ? format : MessageFormat.format(format, parameters), (Throwable) null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package dev.overlord.zomboidforge.core.config;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class ForgeSettingsTest
|
||||
{
|
||||
@TempDir
|
||||
Path directory;
|
||||
|
||||
private ForgeSettings read(String toml) throws Exception
|
||||
{
|
||||
Path file = this.directory.resolve(ForgeSettings.FILE);
|
||||
Files.writeString(file, toml);
|
||||
|
||||
return ForgeSettings.read(file);
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultsWithoutFileOrKeys() throws Exception
|
||||
{
|
||||
assertEquals(ForgeSettings.DEFAULTS, ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE)));
|
||||
assertEquals(ForgeSettings.DEFAULTS, this.read("[main_thread]\n"));
|
||||
assertEquals(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10)), ForgeSettings.DEFAULTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsEveryKey() throws Exception
|
||||
{
|
||||
assertEquals(
|
||||
new ForgeSettings(Duration.ofMillis(5), Duration.ofSeconds(0)),
|
||||
this.read("[main_thread]\nbudget_ms = 5\n\n[shutdown]\ntimeout_s = 0\n")
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsUnknownKeysAndInvalidValues()
|
||||
{
|
||||
IllegalArgumentException unknown = assertThrows(IllegalArgumentException.class, () -> this.read("[main_thread]\nbudget = 5\n[other]\n"));
|
||||
assertEquals("Unknown key 'main_thread.budget'. Unknown key 'other'.", unknown.getMessage());
|
||||
|
||||
IllegalArgumentException range = assertThrows(IllegalArgumentException.class, () -> this.read("[main_thread]\nbudget_ms = 0\n[shutdown]\ntimeout_s = -1\n"));
|
||||
assertEquals("'main_thread.budget_ms' must be at least 1, found 0. 'shutdown.timeout_s' must not be negative, found -1.", range.getMessage());
|
||||
|
||||
IllegalArgumentException type = assertThrows(IllegalArgumentException.class, () -> this.read("[shutdown]\ntimeout_s = \"10\"\n"));
|
||||
assertEquals("'shutdown.timeout_s' must be an integer, found \"10\".", type.getMessage());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package dev.overlord.zomboidforge.core.runtime;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Event;
|
||||
import dev.overlord.zomboidforge.api.Events;
|
||||
import dev.overlord.zomboidforge.api.Subscription;
|
||||
import dev.overlord.zomboidforge.api.TickEvent;
|
||||
import dev.overlord.zomboidforge.core.RecordingLogger;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class EventBusTest
|
||||
{
|
||||
private record Joined(String player) implements Event {}
|
||||
|
||||
private final EventBus bus = new EventBus();
|
||||
private final RecordingLogger logger = new RecordingLogger();
|
||||
private final List<String> received = new ArrayList<>();
|
||||
private final List<Runnable> modTasks = new ArrayList<>();
|
||||
|
||||
/** Collects the tasks for the mod thread instead of running them. */
|
||||
private final Executor modThread = this.modTasks::add;
|
||||
|
||||
@Test
|
||||
void deliversToMainListenersInOrderAndQueuesModThreadListeners()
|
||||
{
|
||||
Events a = this.bus.forMod("a", this.modThread, this.logger);
|
||||
Events b = this.bus.forMod("b", this.modThread, this.logger);
|
||||
|
||||
a.onMain(Joined.class, event -> this.received.add("a main " + event.player()));
|
||||
b.onModThread(Joined.class, event -> this.received.add("b mod thread " + event.player()));
|
||||
b.onMain(Joined.class, event -> this.received.add("b main " + event.player()));
|
||||
|
||||
this.bus.post(new Joined("bob"));
|
||||
|
||||
assertEquals(List.of("a main bob", "b main bob"), this.received);
|
||||
assertEquals(1, this.modTasks.size());
|
||||
|
||||
this.modTasks.getFirst().run();
|
||||
assertEquals("b mod thread bob", this.received.getLast());
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchesTheExactClassAndTracksListeners()
|
||||
{
|
||||
Events a = this.bus.forMod("a", this.modThread, this.logger);
|
||||
Subscription subscription = a.onMain(TickEvent.class, event -> this.received.add("tick " + event.tick()));
|
||||
|
||||
assertTrue(this.bus.hasListeners(TickEvent.class));
|
||||
assertFalse(this.bus.hasListeners(Joined.class));
|
||||
|
||||
this.bus.post(new Joined("bob"));
|
||||
this.bus.post(new TickEvent(3));
|
||||
subscription.cancel();
|
||||
subscription.cancel();
|
||||
this.bus.post(new TickEvent(4));
|
||||
|
||||
assertEquals(List.of("tick 3"), this.received);
|
||||
assertFalse(this.bus.hasListeners(TickEvent.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMainThreadEventsForTheModThread()
|
||||
{
|
||||
Events a = this.bus.forMod("a", this.modThread, this.logger);
|
||||
|
||||
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> a.onModThread(TickEvent.class, event -> {}));
|
||||
assertEquals("'dev.overlord.zomboidforge.api.TickEvent' is a main-thread event; listen with onMain().", e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void removesListenersThatKeepFailing()
|
||||
{
|
||||
Events a = this.bus.forMod("a", this.modThread, this.logger);
|
||||
|
||||
a.onMain(Joined.class, event -> { throw new IllegalStateException("broken"); });
|
||||
a.onMain(Joined.class, event -> this.received.add(event.player()));
|
||||
|
||||
for (int i = 0; i < EventBus.MAX_FAILURES + 2; i++) this.bus.post(new Joined("p" + i));
|
||||
|
||||
assertEquals(EventBus.MAX_FAILURES + 2, this.received.size(), "the other listener keeps receiving");
|
||||
assertEquals(EventBus.MAX_FAILURES + 1, this.logger.messages.size());
|
||||
assertEquals("ERROR: Listener for 'Joined' threw (failure 1 of 10). (java.lang.IllegalStateException: broken)", this.logger.messages.getFirst());
|
||||
assertEquals("ERROR: Listener for 'Joined' removed after 10 failures.", this.logger.messages.getLast());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deliversNothingAfterClose()
|
||||
{
|
||||
this.bus.forMod("a", this.modThread, this.logger).onMain(Joined.class, event -> this.received.add(event.player()));
|
||||
|
||||
this.bus.close();
|
||||
this.bus.post(new Joined("bob"));
|
||||
|
||||
assertTrue(this.received.isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package dev.overlord.zomboidforge.core.runtime;
|
||||
|
||||
import dev.overlord.zomboidforge.api.MainThread;
|
||||
import dev.overlord.zomboidforge.core.RecordingLogger;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** The test thread is the main thread; other threads queue through a helper thread. */
|
||||
class MainThreadQueueTest
|
||||
{
|
||||
private final RecordingLogger logger = new RecordingLogger();
|
||||
private final List<String> ran = new ArrayList<>();
|
||||
|
||||
private MainThreadQueue queue;
|
||||
|
||||
@BeforeEach
|
||||
void setUp()
|
||||
{
|
||||
this.queue = new MainThreadQueue(Duration.ofSeconds(10));
|
||||
this.queue.bindToCurrentThread();
|
||||
}
|
||||
|
||||
/** Runs {@code action} on another thread and waits for it. */
|
||||
private static void fromOtherThread(Runnable action) throws InterruptedException
|
||||
{
|
||||
Thread thread = Thread.ofPlatform().start(action);
|
||||
thread.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
void runsTasksFromOtherThreadsOnTheNextTick() throws Exception
|
||||
{
|
||||
MainThread main = this.queue.forMod("a", this.logger);
|
||||
|
||||
MainThreadQueueTest.fromOtherThread(() -> {
|
||||
assertFalse(main.isMainThread());
|
||||
main.execute(() -> this.ran.add("a1 " + main.isMainThread()));
|
||||
});
|
||||
|
||||
assertTrue(this.ran.isEmpty());
|
||||
|
||||
this.queue.drain();
|
||||
|
||||
assertEquals(List.of("a1 true"), this.ran);
|
||||
assertEquals(1, this.queue.tick());
|
||||
}
|
||||
|
||||
@Test
|
||||
void runsImmediatelyOnTheMainThread() throws Exception
|
||||
{
|
||||
MainThread main = this.queue.forMod("a", this.logger);
|
||||
|
||||
main.execute(() -> this.ran.add("now"));
|
||||
CompletableFuture<Integer> result = main.submit(() -> 42);
|
||||
|
||||
assertEquals(List.of("now"), this.ran);
|
||||
assertEquals(42, result.getNow(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void drainsModsRoundRobin() throws Exception
|
||||
{
|
||||
MainThread a = this.queue.forMod("a", this.logger);
|
||||
MainThread b = this.queue.forMod("b", this.logger);
|
||||
|
||||
MainThreadQueueTest.fromOtherThread(() -> {
|
||||
for (int i = 1; i <= 3; i++) {
|
||||
int n = i;
|
||||
a.execute(() -> this.ran.add("a" + n));
|
||||
}
|
||||
|
||||
b.execute(() -> this.ran.add("b1"));
|
||||
});
|
||||
|
||||
this.queue.drain();
|
||||
|
||||
assertEquals(List.of("a1", "b1", "a2", "a3"), this.ran);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopsAtTheBudgetAndContinuesNextTick() throws Exception
|
||||
{
|
||||
this.queue.budget(Duration.ofMillis(1));
|
||||
|
||||
MainThread a = this.queue.forMod("a", this.logger);
|
||||
MainThread b = this.queue.forMod("b", this.logger);
|
||||
|
||||
MainThreadQueueTest.fromOtherThread(() -> {
|
||||
a.execute(() -> {
|
||||
this.ran.add("a slow");
|
||||
MainThreadQueueTest.sleep(5);
|
||||
});
|
||||
a.execute(() -> this.ran.add("a2"));
|
||||
b.execute(() -> this.ran.add("b1"));
|
||||
});
|
||||
|
||||
this.queue.drain();
|
||||
assertEquals(List.of("a slow"), this.ran, "the slow task used up the budget");
|
||||
|
||||
this.queue.drain();
|
||||
assertEquals(List.of("a slow", "b1", "a2"), this.ran, "the next tick starts with the next mod");
|
||||
}
|
||||
|
||||
@Test
|
||||
void runsDelayedTasksAfterTheirTicks()
|
||||
{
|
||||
MainThread a = this.queue.forMod("a", this.logger);
|
||||
|
||||
a.runLater(2, () -> this.ran.add("later 2"));
|
||||
a.runLater(1, () -> this.ran.add("later 1"));
|
||||
|
||||
this.queue.drain();
|
||||
assertEquals(List.of("later 1"), this.ran);
|
||||
|
||||
this.queue.drain();
|
||||
assertEquals(List.of("later 1", "later 2"), this.ran);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> a.runLater(0, () -> {}));
|
||||
}
|
||||
|
||||
@Test
|
||||
void completesFuturesAndLogsFailedTasks() throws Exception
|
||||
{
|
||||
MainThread a = this.queue.forMod("a", this.logger);
|
||||
List<CompletableFuture<Integer>> futures = new ArrayList<>();
|
||||
|
||||
MainThreadQueueTest.fromOtherThread(() -> {
|
||||
futures.add(a.submit(() -> 7));
|
||||
futures.add(a.submit(() -> { throw new IllegalStateException("submitted"); }));
|
||||
a.execute(() -> { throw new IllegalStateException("executed"); });
|
||||
});
|
||||
|
||||
this.queue.drain();
|
||||
|
||||
assertEquals(7, futures.get(0).get(1, TimeUnit.SECONDS));
|
||||
ExecutionException e = assertThrows(ExecutionException.class, () -> futures.get(1).get(1, TimeUnit.SECONDS));
|
||||
assertEquals("submitted", e.getCause().getMessage());
|
||||
assertEquals(List.of("ERROR: A main-thread task threw. (java.lang.IllegalStateException: executed)"), this.logger.messages);
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeCancelsQueuedTasksAndRejectsNewOnes() throws Exception
|
||||
{
|
||||
MainThread a = this.queue.forMod("a", this.logger);
|
||||
List<CompletableFuture<Integer>> futures = new ArrayList<>();
|
||||
|
||||
MainThreadQueueTest.fromOtherThread(() -> futures.add(a.submit(() -> 7)));
|
||||
a.runLater(1, () -> this.ran.add("later"));
|
||||
|
||||
this.queue.close();
|
||||
this.queue.drain();
|
||||
|
||||
assertTrue(futures.getFirst().isCancelled());
|
||||
assertTrue(this.ran.isEmpty());
|
||||
assertThrows(RejectedExecutionException.class, () -> a.execute(() -> {}));
|
||||
}
|
||||
|
||||
private static void sleep(long millis)
|
||||
{
|
||||
try { Thread.sleep(millis); }
|
||||
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package dev.overlord.zomboidforge.core.runtime;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import jdk.jfr.Recording;
|
||||
import jdk.jfr.consumer.RecordedEvent;
|
||||
import jdk.jfr.consumer.RecordingFile;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
class ModTaskEventTest
|
||||
{
|
||||
@TempDir
|
||||
Path directory;
|
||||
|
||||
@Test
|
||||
void recordsModAndKindAndReturnsFailures() throws Exception
|
||||
{
|
||||
Path recording = this.directory.resolve("tasks.jfr");
|
||||
|
||||
try (Recording jfr = new Recording())
|
||||
{
|
||||
jfr.enable("zomboidforge.ModTask");
|
||||
jfr.start();
|
||||
|
||||
assertNull(ModTaskEvent.run("shop", "task", () -> {}));
|
||||
assertInstanceOf(IllegalStateException.class, ModTaskEvent.run("shop", "listener TickEvent", () -> { throw new IllegalStateException(); }));
|
||||
|
||||
jfr.stop();
|
||||
jfr.dump(recording);
|
||||
}
|
||||
|
||||
List<RecordedEvent> events = RecordingFile.readAllEvents(recording).stream()
|
||||
.filter(event -> event.getEventType().getName().equals("zomboidforge.ModTask"))
|
||||
.toList();
|
||||
|
||||
assertEquals(List.of("shop task", "shop listener TickEvent"), events.stream().map(event -> event.getString("mod") + " " + event.getString("kind")).toList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package dev.overlord.zomboidforge.core.runtime;
|
||||
|
||||
import dev.overlord.zomboidforge.core.RecordingLogger;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ModThreadsTest
|
||||
{
|
||||
private final ModThreads threads = new ModThreads();
|
||||
private final RecordingLogger logger = new RecordingLogger();
|
||||
|
||||
@Test
|
||||
void namesTheThreads() throws Exception
|
||||
{
|
||||
ModThreads.ModExecutors executors = this.threads.create("shop", this.logger);
|
||||
|
||||
Thread modThread = executors.modThread().submit(Thread::currentThread).get(5, TimeUnit.SECONDS);
|
||||
Thread async = executors.async().submit(Thread::currentThread).get(5, TimeUnit.SECONDS);
|
||||
boolean onModThread = executors.modThread().submit(() -> executors.modThread().isModThread()).get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals("zf-mod-shop", modThread.getName());
|
||||
assertTrue(modThread.isDaemon());
|
||||
assertTrue(onModThread);
|
||||
assertFalse(executors.modThread().isModThread());
|
||||
assertTrue(async.isVirtual());
|
||||
assertTrue(async.getName().startsWith("zf-async-shop-"), async.getName());
|
||||
|
||||
this.threads.shutdown(Duration.ofSeconds(5), this.logger);
|
||||
}
|
||||
|
||||
@Test
|
||||
void logsExceptionsOfExecutedTasksAndCompletesSubmittedOnes() throws Exception
|
||||
{
|
||||
ModThreads.ModExecutors executors = this.threads.create("shop", this.logger);
|
||||
CountDownLatch ran = new CountDownLatch(1);
|
||||
|
||||
executors.modThread().execute(() -> { throw new IllegalStateException("executed"); });
|
||||
executors.modThread().execute(ran::countDown);
|
||||
ran.await(5, TimeUnit.SECONDS);
|
||||
|
||||
CompletableFuture<Object> submitted = executors.modThread().submit(() -> { throw new IllegalStateException("submitted"); });
|
||||
ExecutionException e = assertThrows(ExecutionException.class, () -> submitted.get(5, TimeUnit.SECONDS));
|
||||
|
||||
assertEquals("submitted", e.getCause().getMessage());
|
||||
assertEquals(List.of("ERROR: A task on the mod thread threw. (java.lang.IllegalStateException: executed)"), this.logger.messages);
|
||||
|
||||
this.threads.shutdown(Duration.ofSeconds(5), this.logger);
|
||||
}
|
||||
|
||||
@Test
|
||||
void schedulesWithDurations() throws Exception
|
||||
{
|
||||
ModThreads.ModExecutors executors = this.threads.create("shop", this.logger);
|
||||
CountDownLatch runs = new CountDownLatch(3);
|
||||
|
||||
executors.modThread().scheduleAtFixedRate(runs::countDown, Duration.ZERO, Duration.ofMillis(10));
|
||||
|
||||
assertTrue(runs.await(5, TimeUnit.SECONDS));
|
||||
|
||||
this.threads.shutdown(Duration.ofSeconds(5), this.logger);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdownWaitsThenInterrupts() throws Exception
|
||||
{
|
||||
ModThreads.ModExecutors quick = this.threads.create("quick", this.logger);
|
||||
ModThreads.ModExecutors stuck = this.threads.create("stuck", this.logger);
|
||||
|
||||
CountDownLatch started = new CountDownLatch(1);
|
||||
CountDownLatch ended = new CountDownLatch(1);
|
||||
AtomicBoolean interrupted = new AtomicBoolean();
|
||||
AtomicBoolean finished = new AtomicBoolean();
|
||||
|
||||
quick.modThread().execute(() -> {
|
||||
ModThreadsTest.sleep(50);
|
||||
finished.set(true);
|
||||
});
|
||||
|
||||
stuck.modThread().execute(() -> {
|
||||
started.countDown();
|
||||
|
||||
try { Thread.sleep(60_000); }
|
||||
catch (InterruptedException e) { interrupted.set(true); }
|
||||
|
||||
ended.countDown();
|
||||
});
|
||||
|
||||
started.await(5, TimeUnit.SECONDS);
|
||||
this.threads.shutdown(Duration.ofMillis(300), this.logger);
|
||||
|
||||
assertTrue(finished.get(), "running tasks get the timeout to finish");
|
||||
assertTrue(ended.await(5, TimeUnit.SECONDS));
|
||||
assertTrue(interrupted.get());
|
||||
assertEquals(List.of("WARNING: 'stuck': threads still running after 0.3 s; interrupted."), this.logger.messages);
|
||||
assertThrows(RejectedExecutionException.class, () -> quick.modThread().execute(() -> {}));
|
||||
assertThrows(RejectedExecutionException.class, () -> quick.async().execute(() -> {}));
|
||||
}
|
||||
|
||||
private static void sleep(long millis)
|
||||
{
|
||||
try { Thread.sleep(millis); }
|
||||
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package testmods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Event;
|
||||
import dev.overlord.zomboidforge.api.Mod;
|
||||
import dev.overlord.zomboidforge.api.TickEvent;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/**
|
||||
* Entry point that tests package into a mod jar. Counts ticks, hands work from its own thread
|
||||
* to the main thread, and listens for {@link Greeting} on its own thread.
|
||||
*/
|
||||
public final class ThreadMod extends Mod
|
||||
{
|
||||
/** Posted by tests. */
|
||||
public record Greeting(String text) implements Event {}
|
||||
|
||||
/** What happened, with the name of the thread it happened on. */
|
||||
public final List<String> log = new CopyOnWriteArrayList<>();
|
||||
|
||||
public volatile long ticks;
|
||||
|
||||
@Override
|
||||
public void onLoad()
|
||||
{
|
||||
this.events().onMain(TickEvent.class, event -> this.ticks = event.tick());
|
||||
this.events().onModThread(Greeting.class, event -> this.log.add("greeting " + event.text() + " on " + Thread.currentThread().getName()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onServerStarted()
|
||||
{
|
||||
this.modThread().execute(() -> {
|
||||
this.log.add("work on " + Thread.currentThread().getName());
|
||||
this.main().execute(() -> this.log.add("result on " + Thread.currentThread().getName()));
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStopping() { this.log.add("stopping"); }
|
||||
}
|
||||
Reference in new issue
Block a user