Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Utility for running code on the main launch thread at the next available
- * opportunity. There is no guaranteed order that work from various mods will be
- * run, but your own work will be run sequentially.
- * <p>
- * <strong>Use of this class after startup is not possible.</strong> At that
- * point, {@link IThreadListener} should be used instead.
- */
- public class DeferredWorkQueue
- {
- static final ConcurrentLinkedDeque<Runnable> deferredWorkQueue = new ConcurrentLinkedDeque<>();
- private static final Executor deferredExecutor = r -> deferredWorkQueue.add(r);
- private static Throwable lastExceptionRaised;
- private static int exceptionsRaised;
- private static <T> T handleException(Throwable t) {
- LogManager.getLogger(DeferredWorkQueue.class).error("Encountered exception executing deferred work", t);
- lastExceptionRaised = t;
- exceptionsRaised++;
- return null;
- }
- public static CompletableFuture<Void> runLater(Runnable workToEnqueue) {
- return CompletableFuture.runAsync(workToEnqueue, deferredExecutor).exceptionally(DeferredWorkQueue::handleException);
- }
- public static <T> CompletableFuture<T> getLater(Supplier<T> workToEnqueue) {
- return CompletableFuture.supplyAsync(workToEnqueue, deferredExecutor).exceptionally(DeferredWorkQueue::handleException);
- }
- public static <T> CompletableFuture<T> getLaterUnchecked(Callable<T> workToEnqueue) {
- return getLater(() -> {
- try {
- return workToEnqueue.call();
- } catch (Exception e) {
- throw new CompletionException(e);
- }
- });
- }
- static void runTasks() {
- exceptionsRaised = 0;
- lastExceptionRaised = null;
- deferredWorkQueue.forEach(Runnable::run);
- if (lastExceptionRaised != null) {
- throw new LoaderException(exceptionsRaised
- + " exceptions were raised during processing async tasks. The last can be seen in this crash report. All errors were reported in the log.",
- lastExceptionRaised);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment