Signals in Karel

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

Our program will demonstrate how to handle signals in Java. We’ll use a ShutdownHook to gracefully handle termination signals.

import java.util.concurrent.CountDownLatch;

public class Signals {
    public static void main(String[] args) {
        // Create a latch that we'll use to wait for our shutdown signal
        final CountDownLatch done = new CountDownLatch(1);

        // Register a shutdown hook
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                System.out.println();
                System.out.println("Shutdown signal received");
                done.countDown();
            }
        });

        // This could be replaced with actual program logic
        System.out.println("awaiting signal");
        try {
            done.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("exiting");
    }
}

In Java, we don’t have direct equivalents to Unix signals. However, we can use a ShutdownHook to handle termination signals like SIGINT (Ctrl+C) or SIGTERM.

The CountDownLatch is used to block the main thread until our shutdown hook is triggered. This is similar to the channel used in the original example.

When we run this program, it will block waiting for a termination signal. By typing Ctrl+C, we can send a termination signal, causing the program to print the shutdown message and then exit.

$ javac Signals.java
$ java Signals
awaiting signal
^C
Shutdown signal received
exiting

Note that the behavior might slightly differ from the original example. In Java, the JVM handles the OS signals and translates them into shutdown hooks, which provides a more abstract way of dealing with termination signals across different platforms.

This approach demonstrates a way to gracefully shut down a Java application in response to termination signals, which can be useful for cleaning up resources or saving state before the program exits.