有没有办法在Java中记录*每个*线程中断? [英] Is there any way in Java to log *every* Thread interrupt?

查看:107
本文介绍了有没有办法在Java中记录*每个*线程中断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以某种方式记录每次 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.

有没有办法做到这一点?搜索信息,我看到有人提到实施安全管理员的可能性。这是可以在运行时完成的(例如,在Applet或Web Start客户端),还是需要对安装的JVM进行操作?

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?

或有没有更好的方法?

推荐答案

作为一个快速的黑客,这是一个很多比我想象的更容易做。因为这是一个快速的黑客,所以我没有做这样的事情,确保堆栈跟踪足够深,在引用数组之前,等等。我在我签名的Applet的构造函数中插入了以下内容:

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);
      }
    });

dumpThreadStack 方法如下:

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());
}

当然,我永远不会将其留在生产代码中,但足够告诉我哪个线程导致了我没想到的 interrupt()。也就是说,使用这个代码,我得到一个堆栈转储,每次调用 Thread.interrupt()

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().

这篇关于有没有办法在Java中记录*每个*线程中断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆