-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: introduce SignalUtils and fix ctrl+c operation
- Loading branch information
Showing
2 changed files
with
77 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
68 changes: 68 additions & 0 deletions
68
server/src/main/java/org/allaymc/server/utils/SignalUtils.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
package org.allaymc.server.utils; | ||
|
||
import lombok.experimental.UtilityClass; | ||
import lombok.extern.slf4j.Slf4j; | ||
import sun.misc.Signal; | ||
|
||
import java.util.Deque; | ||
import java.util.concurrent.ConcurrentLinkedDeque; | ||
import java.util.concurrent.atomic.AtomicBoolean; | ||
|
||
/** | ||
* @author daoge_cmd | ||
*/ | ||
@Slf4j | ||
@UtilityClass | ||
public class SignalUtils { | ||
|
||
private static final AtomicBoolean TRIGGERED = new AtomicBoolean(false); | ||
private static final AtomicBoolean SIGNAL_REGISTERED = new AtomicBoolean(false); | ||
private static final String[] SIGNAL_LISTEN_TO = {"TERM", "INT"}; | ||
private static final Deque<Runnable> TASKS = new ConcurrentLinkedDeque<>(); | ||
|
||
public static void addTask(Runnable runnable) { | ||
registerSignalIfNeeded(); | ||
TASKS.addLast(runnable); | ||
} | ||
|
||
public static void addTaskToFirst(Runnable runnable) { | ||
registerSignalIfNeeded(); | ||
TASKS.addFirst(runnable); | ||
} | ||
|
||
private static void registerSignalIfNeeded() { | ||
if (!SIGNAL_REGISTERED.getAndSet(true)) { | ||
registerTermSignalIfNeeded(); | ||
} | ||
} | ||
|
||
private static void registerTermSignalIfNeeded() { | ||
for (var name : SIGNAL_LISTEN_TO) { | ||
Signal.handle(new Signal(name), signal -> { | ||
log.info("Signal {} received", name); | ||
|
||
if (TRIGGERED.getAndSet(true)) { | ||
return; | ||
} | ||
|
||
try { | ||
doTasks(); | ||
System.exit(0); | ||
} catch (Throwable t) { | ||
log.error("Error while executing shutdown tasks", t); | ||
System.exit(1); | ||
} | ||
}); | ||
} | ||
} | ||
|
||
private static void doTasks() { | ||
for (Runnable runnable : TASKS) { | ||
try { | ||
runnable.run(); | ||
} catch (Throwable t) { | ||
log.error("Error while executing shutdown task: {}", runnable, t); | ||
} | ||
} | ||
} | ||
} |