Alternative to sun.misc.Signal

plancys picture plancys · Oct 31, 2013 · Viewed 12.3k times · Source

I started research to find an alternative to the sun.misc.Signal class, because it could be unsupported in upcoming JDKs (we're currently working on 1.6). When I build the project I get:

warning: sun.misc.SignalHandler is Sun proprietary API and may be removed in a future release

I came across multiple solutions but they don't fit my project e.g. in this question.

This is unacceptable in my situation because:

  • Signals are used not only for killing application
  • The application is huge - every conceptual change of communication between modules/JVMs could take years to implement

Thus, the desirable solution is to find something like a new Oracle version of this class or something which works in the same way. Does such a solution exist?

Answer

dimo414 picture dimo414 · Dec 9, 2015

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.