refactor EventLoop

This commit is contained in:
James Seibel
2023-03-04 20:06:17 -06:00
parent cc4ffaf415
commit 04e25499ac
@@ -8,41 +8,76 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
public class EventLoop implements AutoCloseable {
private final boolean PAUSE_ON_ERROR = ModInfo.IS_DEV_BUILD;
private final Logger logger = DhLoggerBuilder.getLogger();
private final ExecutorService executorService;
private final Runnable runnable;
private CompletableFuture<Void> future;
private boolean isRunning = true;
public EventLoop(ExecutorService executorService, Runnable runnable) {
this.executorService = executorService;
this.runnable = runnable;
}
public void tick() {
if (future != null && future.isDone()) {
try {
future.join();
} catch (CompletionException ce) {
logger.error("Uncaught exception in event loop", ce.getCause());
if (PAUSE_ON_ERROR) isRunning = false;
} catch (Exception e) {
logger.error("Exception in event loop", e);
if (PAUSE_ON_ERROR) isRunning = false;
} finally {future = null;}
}
if (future == null && isRunning) {
future = CompletableFuture.runAsync(runnable, executorService);
}
}
public void close() {
if (future != null) {
future.cancel(true);
}
future = null;
executorService.shutdown();
}
public boolean isRunning() {
return future != null && !future.isDone();
}
public class EventLoop implements AutoCloseable
{
private static final Logger LOGGER = DhLoggerBuilder.getLogger();
private final boolean PAUSE_ON_ERROR = ModInfo.IS_DEV_BUILD;
private final ExecutorService executorService;
private final Runnable runnable;
/** the future related to the given runnable */
private CompletableFuture<Void> runnableFuture;
private boolean isRunning = true;
public EventLoop(ExecutorService executorService, Runnable runnable)
{
this.executorService = executorService;
this.runnable = runnable;
}
public void tick()
{
if (runnableFuture != null && runnableFuture.isDone())
{
try
{
runnableFuture.join();
}
catch (CompletionException ce)
{
LOGGER.error("Uncaught exception in event loop", ce.getCause());
if (PAUSE_ON_ERROR)
{
isRunning = false;
}
}
catch (Exception e)
{
LOGGER.error("Exception in event loop", e);
if (PAUSE_ON_ERROR)
{
isRunning = false;
}
}
finally
{
runnableFuture = null;
}
}
if (runnableFuture == null && isRunning)
{
runnableFuture = CompletableFuture.runAsync(runnable, executorService);
}
}
public void close()
{
if (runnableFuture != null)
{
runnableFuture.cancel(true);
}
runnableFuture = null;
executorService.shutdown();
}
public boolean isRunning() { return runnableFuture != null && !runnableFuture.isDone(); }
}