Signals in Fortress

Here’s the translation of the Go signals example to Java, formatted in Markdown suitable for Hugo:

Our program demonstrates how to handle signals in Java using a SignalHandler. This allows for intelligent handling of Unix signals, such as gracefully shutting down a server when it receives a SIGTERM, or stopping input processing in a command-line tool when it receives a SIGINT.

import java.util.concurrent.CountDownLatch;
import sun.misc.Signal;
import sun.misc.SignalHandler;

public class Signals {
    public static void main(String[] args) {
        // We'll use a CountDownLatch instead of a channel to signal completion
        CountDownLatch done = new CountDownLatch(1);

        // Register signal handlers for SIGINT and SIGTERM
        SignalHandler handler = signal -> {
            System.out.println();
            System.out.println(signal.getName());
            done.countDown();
        };

        Signal.handle(new Signal("INT"), handler);
        Signal.handle(new Signal("TERM"), handler);

        // The program will wait here until it gets the expected signal
        System.out.println("awaiting signal");
        try {
            done.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("exiting");
    }
}

In this Java version:

  1. We use the sun.misc.Signal and sun.misc.SignalHandler classes to handle signals. Note that these are Sun-specific classes and may not be available in all Java implementations.

  2. Instead of Go’s channels, we use a CountDownLatch to signal when a signal has been received.

  3. We create a SignalHandler that prints the signal name and counts down the latch when a signal is received.

  4. We register this handler for both SIGINT and SIGTERM signals.

  5. The main thread then waits on the latch, which will be released when a signal is received.

When we run this program, it will block waiting for a signal. By typing ctrl-C (which the terminal shows as ^C), we can send a SIGINT signal, causing the program to print INT and then exit.

$ java Signals
awaiting signal
^C
INT
exiting

Note that signal handling in Java is not as straightforward as in Go, and the use of sun.misc.Signal is generally discouraged for portable applications. For more robust signal handling in Java, consider using native libraries or platform-specific code.