| 1 | package net.minecraft.util.thread;
|
| 2 |
|
| 3 | import com.google.common.collect.ImmutableList;
|
| 4 | import com.google.common.collect.Queues;
|
| 5 | import com.mojang.jtracy.TracyClient;
|
| 6 | import com.mojang.jtracy.Zone;
|
| 7 | import com.mojang.logging.LogUtils;
|
| 8 | import java.util.List;
|
| 9 | import java.util.Queue;
|
| 10 | import java.util.concurrent.CompletableFuture;
|
| 11 | import java.util.concurrent.Executor;
|
| 12 | import java.util.concurrent.locks.LockSupport;
|
| 13 | import java.util.function.BooleanSupplier;
|
| 14 | import java.util.function.Supplier;
|
| 15 | import javax.annotation.CheckReturnValue;
|
| 16 | import net.minecraft.CrashReport;
|
| 17 | import net.minecraft.ReportedException;
|
| 18 | import net.minecraft.SharedConstants;
|
| 19 | import net.minecraft.util.profiling.metrics.MetricCategory;
|
| 20 | import net.minecraft.util.profiling.metrics.MetricSampler;
|
| 21 | import net.minecraft.util.profiling.metrics.MetricsRegistry;
|
| 22 | import net.minecraft.util.profiling.metrics.ProfilerMeasured;
|
| 23 | import org.jspecify.annotations.Nullable;
|
| 24 | import org.slf4j.Logger;
|
| 25 |
|
| 26 | public abstract class BlockableEventLoop<R extends Runnable> implements Executor, TaskScheduler<R>, ProfilerMeasured {
|
| 27 | public static final long BLOCK_TIME_NANOS = 100000L;
|
| 28 | private static volatile @Nullable Supplier<CrashReport> delayedCrash;
|
| 29 | private final boolean propagatesCrashes;
|
| 30 | private final String name;
|
| 31 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 32 | private final Queue<R> pendingRunnables = Queues.newConcurrentLinkedQueue();
|
| 33 | private int blockingCount;
|
| 34 |
|
| 35 | protected BlockableEventLoop(final String name, final boolean propagatesCrashes) {
|
| 36 | this.propagatesCrashes = propagatesCrashes;
|
| 37 | this.name = name;
|
| 38 | MetricsRegistry.INSTANCE.add(this);
|
| 39 | }
|
| 40 |
|
| 41 | protected abstract boolean shouldRun(final R task);
|
| 42 |
|
| 43 | public boolean isSameThread() {
|
| 44 | return Thread.currentThread() == this.getRunningThread();
|
| 45 | }
|
| 46 |
|
| 47 | protected abstract Thread getRunningThread();
|
| 48 |
|
| 49 | protected boolean scheduleExecutables() {
|
| 50 | return !this.isSameThread();
|
| 51 | }
|
| 52 |
|
| 53 | public int getPendingTasksCount() {
|
| 54 | return this.pendingRunnables.size();
|
| 55 | }
|
| 56 |
|
| 57 | @Override
|
| 58 | public String name() {
|
| 59 | return this.name;
|
| 60 | }
|
| 61 |
|
| 62 | public <V> CompletableFuture<V> submit(final Supplier<V> supplier) {
|
| 63 | return this.scheduleExecutables() ? CompletableFuture.supplyAsync(supplier, this) : CompletableFuture.completedFuture(supplier.get());
|
| 64 | }
|
| 65 |
|
| 66 | private CompletableFuture<Void> submitAsync(final Runnable runnable) {
|
| 67 | return CompletableFuture.supplyAsync(() -> {
|
| 68 | runnable.run();
|
| 69 | return null;
|
| 70 | }, this);
|
| 71 | }
|
| 72 |
|
| 73 | @CheckReturnValue
|
| 74 | public CompletableFuture<Void> submit(final Runnable runnable) {
|
| 75 | if (this.scheduleExecutables()) {
|
| 76 | return this.submitAsync(runnable);
|
| 77 | }
|
| 78 |
|
| 79 | runnable.run();
|
| 80 | return CompletableFuture.completedFuture(null);
|
| 81 | }
|
| 82 |
|
| 83 | public void executeBlocking(final Runnable runnable) {
|
| 84 | if (!this.isSameThread()) {
|
| 85 | this.submitAsync(runnable).join();
|
| 86 | } else {
|
| 87 | runnable.run();
|
| 88 | }
|
| 89 | }
|
| 90 |
|
| 91 | @Override
|
| 92 | public void schedule(final R r) {
|
| 93 | this.pendingRunnables.add(r);
|
| 94 | LockSupport.unpark(this.getRunningThread());
|
| 95 | }
|
| 96 |
|
| 97 | @Override
|
| 98 | public void execute(final Runnable command) {
|
| 99 | R task = this.wrapRunnable(command);
|
| 100 | if (this.scheduleExecutables()) {
|
| 101 | this.schedule(task);
|
| 102 | } else {
|
| 103 | this.doRunTask(task);
|
| 104 | }
|
| 105 | }
|
| 106 |
|
| 107 | public void executeIfPossible(final Runnable command) {
|
| 108 | this.execute(command);
|
| 109 | }
|
| 110 |
|
| 111 | protected void dropAllTasks() {
|
| 112 | this.pendingRunnables.clear();
|
| 113 | }
|
| 114 |
|
| 115 | protected void runAllTasks() {
|
| 116 | while (this.pollTask()) {
|
| 117 | }
|
| 118 | }
|
| 119 |
|
| 120 | protected boolean shouldRunAllTasks() {
|
| 121 | return this.blockingCount > 0;
|
| 122 | }
|
| 123 |
|
| 124 | protected boolean pollTask() {
|
| 125 | this.throwDelayedException();
|
| 126 | R task = this.pendingRunnables.peek();
|
| 127 | if (task == null) {
|
| 128 | return false;
|
| 129 | }
|
| 130 |
|
| 131 | if (!this.shouldRunAllTasks() && !this.shouldRun(task)) {
|
| 132 | return false;
|
| 133 | }
|
| 134 |
|
| 135 | this.doRunTask(this.pendingRunnables.remove());
|
| 136 | return true;
|
| 137 | }
|
| 138 |
|
| 139 | public void managedBlock(final BooleanSupplier condition) {
|
| 140 | this.blockingCount++;
|
| 141 |
|
| 142 | try {
|
| 143 | while (!condition.getAsBoolean()) {
|
| 144 | if (!this.pollTask()) {
|
| 145 | this.waitForTasks();
|
| 146 | }
|
| 147 | }
|
| 148 | } finally {
|
| 149 | this.blockingCount--;
|
| 150 | }
|
| 151 | }
|
| 152 |
|
| 153 | protected void waitForTasks() {
|
| 154 | Thread.yield();
|
| 155 | LockSupport.parkNanos("waiting for tasks", 100000L);
|
| 156 | }
|
| 157 |
|
| 158 | protected void doRunTask(final R task) {
|
| 159 | try (Zone ignored = TracyClient.beginZone("Task", SharedConstants.IS_RUNNING_IN_IDE)) {
|
| 160 | task.run();
|
| 161 | } catch (Exception e) {
|
| 162 | LOGGER.error(LogUtils.FATAL_MARKER, "Error executing task on {}", this.name(), e);
|
| 163 | if (isNonRecoverable(e)) {
|
| 164 | throw e;
|
| 165 | }
|
| 166 | }
|
| 167 | }
|
| 168 |
|
| 169 | @Override
|
| 170 | public List<MetricSampler> profiledMetrics() {
|
| 171 | return ImmutableList.of(MetricSampler.create(this.name + "-pending-tasks", MetricCategory.EVENT_LOOPS, this::getPendingTasksCount));
|
| 172 | }
|
| 173 |
|
| 174 | public static boolean isNonRecoverable(final Throwable t) {
|
| 175 | return t instanceof ReportedException r ? isNonRecoverable(r.getCause()) : t instanceof OutOfMemoryError || t instanceof StackOverflowError;
|
| 176 | }
|
| 177 |
|
| 178 | private void throwDelayedException() {
|
| 179 | if (this.propagatesCrashes) {
|
| 180 | Supplier<CrashReport> delayedCrash = BlockableEventLoop.delayedCrash;
|
| 181 | if (delayedCrash != null) {
|
| 182 | throw new ReportedException(delayedCrash.get());
|
| 183 | }
|
| 184 | }
|
| 185 | }
|
| 186 |
|
| 187 | public void delayCrash(final CrashReport crashReport) {
|
| 188 | delayedCrash = () -> crashReport;
|
| 189 | }
|
| 190 |
|
| 191 | public static synchronized void relayDelayCrash(final CrashReport crashReport) {
|
| 192 | Supplier<CrashReport> delayedCrash = BlockableEventLoop.delayedCrash;
|
| 193 | if (delayedCrash == null) {
|
| 194 | BlockableEventLoop.delayedCrash = () -> crashReport;
|
| 195 | } else {
|
| 196 | delayedCrash.get().getException().addSuppressed(crashReport.getException());
|
| 197 | }
|
| 198 | }
|
| 199 | }
|
| 200 |
|