Monday, June 25, 2007

Signals and Java

Ooookay. You are now, presumably, fresh from reading the original post about using AsyncGetCallTrace and the more recent post about how to use SIGPROF in C++. The next obvious question is...

Can I Register a Signal Handler in Java?

Um... Kind of!

There is an undocumented and unsupported interface called sun.misc.Signal present in most Java implementations. For those of you who have downloaded the JDK, the files live in /src/share/classes/sun/misc.

If you import sun.misc.Signal and sun.misc.SignalHandler, you can define a signal handler like this:

// Handles SIGHUP
Signal.handle(new Signal("HUP"), new SignalHandler() {
// Signal handler method
public void handle(Signal signal) {
System.out.println("Got signal" + signal);
}
});

You can raise a signal like this:

Signal.raise(new Signal("HUP"));

You can even register a native signal handler with the Signal.handle0 method (I'll leave that as an exercise for the reader).

Having said that, none of this helps us set timers or do profiling, really. It's just an interesting aside.

5 comments:

Anonymous said...

so true...

Anonymous said...

so very true...

Anonymous said...

so very very true...

junchao said...

Hi, hope you can see my message.
I am trying to ues signal in java. But I am afraid the signalhandler is taged with deprecated annotation. Should I still can use it ? I am doing business products, so I don't want the user find my product fails when he upgrade the jvm. Please write to a email. junchaowu@163.com

Jeremy Manson said...

It's been in there for a while, so it unlikely to go away. Having said that, it isn't compatible with other Java implementations, and it might go away. Use at your own risk.