tterrag1098

Untitled

Jan 14th, 2019
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1.  
  2. /**
  3. * Utility for running code on the main launch thread at the next available
  4. * opportunity. There is no guaranteed order that work from various mods will be
  5. * run, but your own work will be run sequentially.
  6. * <p>
  7. * <strong>Use of this class after startup is not possible.</strong> At that
  8. * point, {@link IThreadListener} should be used instead.
  9. */
  10. public class DeferredWorkQueue
  11. {
  12. static final ConcurrentLinkedDeque<Runnable> deferredWorkQueue = new ConcurrentLinkedDeque<>();
  13. private static final Executor deferredExecutor = r -> deferredWorkQueue.add(r);
  14.  
  15. private static Throwable lastExceptionRaised;
  16. private static int exceptionsRaised;
  17.  
  18. private static <T> T handleException(Throwable t) {
  19. LogManager.getLogger(DeferredWorkQueue.class).error("Encountered exception executing deferred work", t);
  20. lastExceptionRaised = t;
  21. exceptionsRaised++;
  22. return null;
  23. }
  24.  
  25. public static CompletableFuture<Void> runLater(Runnable workToEnqueue) {
  26. return CompletableFuture.runAsync(workToEnqueue, deferredExecutor).exceptionally(DeferredWorkQueue::handleException);
  27. }
  28.  
  29. public static <T> CompletableFuture<T> getLater(Supplier<T> workToEnqueue) {
  30. return CompletableFuture.supplyAsync(workToEnqueue, deferredExecutor).exceptionally(DeferredWorkQueue::handleException);
  31. }
  32.  
  33. public static <T> CompletableFuture<T> getLaterUnchecked(Callable<T> workToEnqueue) {
  34. return getLater(() -> {
  35. try {
  36. return workToEnqueue.call();
  37. } catch (Exception e) {
  38. throw new CompletionException(e);
  39. }
  40. });
  41. }
  42.  
  43. static void runTasks() {
  44. exceptionsRaised = 0;
  45. lastExceptionRaised = null;
  46. deferredWorkQueue.forEach(Runnable::run);
  47. if (lastExceptionRaised != null) {
  48. throw new LoaderException(exceptionsRaised
  49. + " exceptions were raised during processing async tasks. The last can be seen in this crash report. All errors were reported in the log.",
  50. lastExceptionRaised);
  51. }
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment