Signals in Logo

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 and sun.misc.SignalHandler classes to handle SIGINT and SIGTERM signals.

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 simulates the main program logic
        Thread mainThread = new Thread(() -> {
            System.out.println("awaiting signal");
            while (!done[0]) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("exiting");
        });

        mainThread.start();

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

In this Java version, we use the sun.misc.Signal and sun.misc.SignalHandler classes to handle signals. These classes are not part of the standard Java API and are considered internal APIs, so they may not be available in all Java environments.

We create a SignalHandler that prints the received signal and sets a boolean flag to indicate that the program should exit. We then register this handler for both SIGINT and SIGTERM signals.

The main program logic is simulated in a separate thread. This thread continuously checks the done flag and exits when it becomes true. This approach is similar to the goroutine used in the original example.

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.

$ javac SignalsExample.java
$ java SignalsExample
awaiting signal
^C
INT
exiting

Note that the exact behavior may vary depending on the Java runtime environment and the operating system. Also, using sun.misc.Signal is not recommended for production code as it’s not part of the standard Java API. For more robust signal handling in Java, consider using native libraries or other platform-specific solutions.