Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way in Java to log *every* Thread interrupt?

I would like to somehow log every time Thread.interrupt() is called, logging which Thread issued the call (and its current stack) as well as identifying information about which Thread is being interrupted.

Is there a way to do this? Searching for information, I saw someone reference the possibility of implementing a security manager. Is this something that can be done at runtime (e.g., in an Applet or Web Start client), or do you need to tool the installed JVM to do this?

Or is there a better way to do this?

like image 487
Eddie Avatar asked Apr 28 '09 17:04

Eddie


1 Answers

As a quick hack, this was a lot easier to do than I thought it would be. Since this is a quick hack, I didn't do things like ensure that the stack trace is deep enough before dereferencing the array, etc. I inserted the following in my signed Applet's constructor:

log.info("Old security manager = " + System.getSecurityManager());
System.setSecurityManager(new SecurityManager() {
      @Override
      public void checkAccess(final Thread t) {
        StackTraceElement[] list = Thread.currentThread().getStackTrace();
        StackTraceElement element = list[3];
        if (element.getMethodName().equals("interrupt")) {
          log.info("CheckAccess to interrupt(Thread = " + t.getName() + ") - "
                   + element.getMethodName());
          dumpThreadStack(Thread.currentThread());
        }
        super.checkAccess(t);
      }
    });

and the dumpThreadStack method is as follows:

public static void dumpThreadStack(final Thread thread) {
  StringBuilder builder = new StringBuilder('\n');
  try {
    for (StackTraceElement element : thread.getStackTrace()) {
      builder.append(element.toString()).append('\n');
    }
  } catch (SecurityException e) { /* ignore */ }
  log.info(builder.toString());
}

I could never, of course, leave this in production code, but it sufficed to tell me exactly which thread was causing an interrupt() that I didn't expect. That is, with this code in place, I get a stack dump for every call to Thread.interrupt().

like image 70
Eddie Avatar answered Sep 20 '22 00:09

Eddie