Signal Introduction
A signal is a simulation of the interrupt mechanism at the software level. In principle, a process receives a signal and the processor receives an interrupt request.
In general, signals are an asynchronous communication mechanism between processes.
Typical Example:
Kill-s sigkill PID (that is, kill-9 PID) immediately kills the process of the specified PID.
In the above example, sigkill is the signal sent to the PID process.
Platform relevance
Signals are platform-related, and the types of signals that can be used on different platforms are different.
Supported signals in Linux (view the description of the comparison signal List)
Segv, ill, FPE, bus, sys, CPU, fsz, abrt, Int, term, hup, usr1, usr2, quit, break, trap, pipe
Supported signals in Windows
Segv, ill, FPE, abrt, Int, term, break
Signal Selection
To avoid interfering with normal signal operations and simulating Java asynchronous notifications, We need to select a special signal first.
By viewing the description on the signal list, it is found that SIGUSR1 and sigusr2 are user-defined signals.
Then, theoretically, they will not affect normal functions.
Here I chose usr2 as the signal transmission. The reason is that usr1 may be occupied by other apps.
Instance code
import sun.misc.Signal;import sun.misc.SignalHandler;/** * Java Signal Test * @author Ken Wu * */@SuppressWarnings("restriction")public class TestSignal implements SignalHandler { private void signalCallback(Signal sn) { System.out.println(sn.getName() + "is recevied."); } @Override public void handle(Signal signalName) { signalCallback(signalName); } public static void main(String[] args) throws InterruptedException { TestSignal testSignalHandler = new TestSignal(); // install signals Signal sig = new Signal("USR2"); Signal.handle(sig, testSignalHandler); Thread.sleep(15000); }}Sun provides us with two tool classes to facilitate the installation and replacement of signal processors.
Sun. Misc. Signal
Sun. Misc. signalhandler
After the above Code is compiled, it will be paused for 15 seconds. At this time, it is the best time for you to send a signal to the Java Process.
Before sending a signal, you must first obtain the Java Process ID through PS or JPS, and then run
kill -s SIGUSR2 pid
If sigusr2 is recevied is displayed in Java stdout, the signal is successfully delivered.
Actual benefits of using signals in Java programmingAs the most primitive asynchronous communication means between processes, signals have many limitations, such as the inability to transmit context, the signal may be occupied at any time, resulting in conflicts and lack of scalability, therefore, for functional requirements, using it has little benefits.
Of course, the signal is not useless. In addition to being used as a simple asynchronous notification, it can also use its process event notification function.
A typical example in Java is shutdownhook.