| 1 | package net.minecraft.server.rcon.thread;
|
| 2 |
|
| 3 | import com.mojang.logging.LogUtils;
|
| 4 | import java.util.concurrent.atomic.AtomicInteger;
|
| 5 | import net.minecraft.DefaultUncaughtExceptionHandlerWithName;
|
| 6 | import org.jspecify.annotations.Nullable;
|
| 7 | import org.slf4j.Logger;
|
| 8 |
|
| 9 | public abstract class GenericThread implements Runnable {
|
| 10 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 11 | private static final AtomicInteger UNIQUE_THREAD_ID = new AtomicInteger(0);
|
| 12 | private static final int MAX_STOP_WAIT = 5;
|
| 13 | protected volatile boolean running;
|
| 14 | protected final String name;
|
| 15 | protected @Nullable Thread thread;
|
| 16 |
|
| 17 | protected GenericThread(final String name) {
|
| 18 | this.name = name;
|
| 19 | }
|
| 20 |
|
| 21 | public synchronized boolean start() {
|
| 22 | if (this.running) {
|
| 23 | return true;
|
| 24 | }
|
| 25 |
|
| 26 | this.running = true;
|
| 27 | this.thread = new Thread(this, this.name + " #" + UNIQUE_THREAD_ID.incrementAndGet());
|
| 28 | this.thread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandlerWithName(LOGGER));
|
| 29 | this.thread.start();
|
| 30 | LOGGER.info("Thread {} started", this.name);
|
| 31 | return true;
|
| 32 | }
|
| 33 |
|
| 34 | public synchronized void stop() {
|
| 35 | this.running = false;
|
| 36 | if (null != this.thread) {
|
| 37 | int waited = 0;
|
| 38 |
|
| 39 | while (this.thread.isAlive()) {
|
| 40 | try {
|
| 41 | this.thread.join(1000L);
|
| 42 | if (++waited >= 5) {
|
| 43 | LOGGER.warn("Waited {} seconds attempting force stop!", waited);
|
| 44 | } else if (this.thread.isAlive()) {
|
| 45 | LOGGER.warn("Thread {} ({}) failed to exit after {} second(s)", this, this.thread.getState(), waited, new Exception("Stack:"));
|
| 46 | this.thread.interrupt();
|
| 47 | }
|
| 48 | } catch (InterruptedException var3) {
|
| 49 | }
|
| 50 | }
|
| 51 |
|
| 52 | LOGGER.info("Thread {} stopped", this.name);
|
| 53 | this.thread = null;
|
| 54 | }
|
| 55 | }
|
| 56 |
|
| 57 | public boolean isRunning() {
|
| 58 | return this.running;
|
| 59 | }
|
| 60 | }
|
| 61 |
|