Alternative to sun.misc.Signal

As you will find repeated ad infinitum when learning about signal handling in Java, you are encouraged to avoid writing Java code that depends directly on signals. The general best practice is to allow the JVM to exit normally on ctrl+c and other signals by registering a shutdown hook instead. Handling signals directly makes your Java program OS-dependent.

But sometimes that’s OK, and you really, really do want to handle signals yourself.

Even though it’s not exposed as part of the official JDK API, some part of the JVM has to handle signals (in order to trigger the shutdown hooks and exit), and that component is sun.misc.Signal. Although this is an implementation detail and therefore could change, it is unlikely in practice. If it were to change, it would need to be replaced with an equivalent mechanism, and likely documented in the Java Platform Troubleshooting Guide.

The sibling class sun.misc.Unsafe is widely used and is similarly undocumented. There is active work towards trying to remove this class because it’s “become a ‘dumping ground’ for non-standard, yet necessary, methods“, but the current proposal, while limiting some non-standard APIs, keeps both sun.misc.Unsafe and sun.misc.Signal available by default. An earlier plan to actually prevent access to these classes would still have included a command-line flag to allow access to them for backwards-compatibility.

In short while you cannot rely on sun.misc.Signal and must plan for the eventuality that this behavior changes, it is highly unlikely that this behavior will change before JDK 10, and if it does either a new, better mechanism will probably be introduced or there will be a reasonable way to re-enable it if needed.

However it would be wise to compartmentalize the code that relies on any sun.misc classes to as small a scope as possible – create a wrapping API for signal handling so that callers don’t need to interact directly with sun.misc. That way if the API changes you only need to change the implementation of your wrapper, rather than all your signal handling code.

Leave a Comment