Signals in Squirrel

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. We’ll use the sun.misc.Signal class to register a signal handler for SIGINT (Ctrl+C) and SIGTERM.

import sun.misc.Signal;
import sun.misc.SignalHandler;

public class SignalsExample {
    public static void main(String[] args) {
        // Create a boolean to indicate when the program should exit
        final boolean[] done = {false};

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

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

        // This thread will wait for a signal
        Thread signalThread = new Thread(() -> {
            while (!done[0]) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        signalThread.start();

        System.out.println("awaiting signal");

        try {
            signalThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("exiting");
    }
}

In this Java version, we use the sun.misc.Signal class to register signal handlers. Note that this is a Sun-specific API and may not be available in all Java implementations.

We create a boolean array done to indicate when the program should exit. We use an array because we need a mutable boolean that can be accessed from within the lambda expression.

The signal handler is implemented as a lambda expression that prints the signal name and sets the done flag to true.

We register this handler for both SIGINT and SIGTERM signals.

Instead of using channels like in the original example, we create a separate thread that continuously checks the done flag. This thread will exit when a signal is received and the flag is set to true.

The main thread waits for the signal thread to complete using join().

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 SignalsExample
awaiting signal
^C
INT
exiting

Note that Java’s signal handling capabilities are more limited compared to some other languages, 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.