服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

驯服tiger之线程中的默认异常处理


  跟踪无法预期的运行时异常可能是一件又慢又费力的事情,只获得默认线程名称和堆栈跟踪通常是不够的。在文中,java 开发人员 john zukowski 向您展示了如何通过替代默认行为来定制输出。他还对比了通过细分 threadgroup 定制输出的老方法与通过提供自己的 uncaughtexceptionhandler 定制输出的新方法。

  虽然我们不想创建在无法预期时抛出运行时异常的程序,但这种情况还是会发生――尤其是第一次运行复杂程序时。通常是使用默认行为、打印堆栈溢出和结束线程的生命来处理这些异常。

  从哪里发现默认行为?每个线程都属于一个由 java.lang.threadgroup 类表示的线程组。顾名思义,线程组允许您将线程组合在一起。您可能是为了方便而将线程组合,例如,一个线程池中的所有线程都属于组 x,而另一个池的所有线程则属于组 y,或者是为了访问控制而将线程进行组合。组 x 中的线程无权访问或改变组 y 中的线程,除非它们都在同一线程组内(或在一个子组内)。

  在 tiger 之前, threadgroup 类提供了一种处理未捕获异常的方法: threadgroup 的 uncaughtexception() 方法。如果异常不是 threaddeath ,则将线程的名称和堆栈回溯(stack backtrace)发送到 system.err 。但是 tiger 添加了另一种方法: thread.uncaughtexceptionhandler 接口。细分 threadgroup 或安装该新接口的实现都允许您更改默认行为。我们将对 tiger 之前和之后提供的方法都进行研究。

  使用 threadgroup 的定制行为

  发生未捕获的异常时,默认行为是将堆栈溢出打印输出到系统错误( system.err )中,如清单 1 中所示。不需要使用任何命令参数来启动程序。

  清单 1. 线程溢出示例

public class simpledump {
 public static void main(string args[]) {
  system.out.println(args[0]);
 }
}

  不使用任何参数运行该程序将生成清单 2 中的输出。尽管它不是一个很长的堆栈跟踪,但它是一个完整的堆栈跟踪。

  清单 2. 默认线程溢出输出

exception in thread "main" java.lang.arrayindexoutofboundsexception: 0
at simpledump.main(simpledump.java:3)

  正如 java 平台的许多东西一样,如果不喜欢默认行为,您可以对其进行更改。在 java 平台的 tiger 版以前的版本中,不能替代所有线程的默认行为,但是可以创建一个新的 threadgroup ,并更改在该组内创建的任何线程的默认行为。您可以重写 uncaughtexception(thread t, throwable e) 方法来定制该行为。然后,当发生未预料的运行时异常时,该线程组内创建的任何线程都将获得新的行为。不过,最好是修复基础问题,我将提供一个简单的示例,说明更改默认行为所必需的步骤。清单 3 展示了将执行代码放入新线程的调整过的测试程序:

  清单 3. 调整过的线程溢出示例

public class windowdump {
 public static void main(string args[]) throws exception {
  threadgroup group = new loggingthreadgroup("logger");
  new thread(group, "mythread") {
   public void run() {
    system.out.println(1 / 0);
   }
  }.start();
 }
}

  loggingthreadgroup 类是一个新的内容,清单 4 中显示了它的定义。为了进行说明,通过重写 uncaughtexception() 方法实现的特殊行为将在一个弹出窗口中显示该异常,这项操作是在特殊 handler 的帮助下使用 java logging api 来完成的。

  清单 4. loggingthreadgroup 的定义

import java.util.logging.*;

public class loggingthreadgroup extends threadgroup {
 private static logger logger;
 public loggingthreadgroup(string name) {
  super(name);
 }
 public void uncaughtexception(thread t, throwable e) {
  // initialize logger once
  if (logger == null) {
   logger = logger.getlogger("example");
   handler handler = loggingwindowhandler.getinstance();
   logger.addhandler(handler);
  }
  logger.log(level.warning, t.getname(), e);
 }
}

  这里创建的定制 handler 的类型为 loggingwindowhandler ,该类型的定义在清单 5 中。处理程序使用了一个支持类 loggingwindow ,该类将异常显示在屏幕上。 清单 6 中显示了该类的定义。 handler 的 public void publish(logrecord record) 方法实现了一些重要操作。其余操作大部分只与配置有关。

  清单 5. loggingwindowhandler 的定义

import java.util.logging.*;

public class loggingwindowhandler extends handler {
 private static loggingwindow window;
 private static loggingwindowhandler handler;

 private loggingwindowhandler() {
  configure();
  window = new loggingwindow("logging window...", 400, 200);
 }

 public static synchronized loggingwindowhandler getinstance() {
  if (handler == null) {
   handler = new loggingwindowhandler();
  }
  return handler;
 }

 /**
 * get any configuration properties set
 */
 private void configure() {
  logmanager manager = logmanager.getlogmanager();
  string classname = getclass().getname();
  string level = manager.getproperty(classname + ".level");
  setlevel((level == null) ? level.info : level.parse(level));
  string filter = manager.getproperty(classname + ".filter");
  setfilter(makefilter(filter));
  string formatter = manager.getproperty(classname + ".formatter");
  setformatter(makeformatter(formatter));
 }

 private filter makefilter(string name) {
  filter f = null;
  try {
   class c = class.forname(name);
   f = (filter)c.newinstance();
  } catch (exception e) {
   if (name != null) {
    system.err.println("unable to load filter: " + name);
   }
  }
  return f;
 }

 private formatter makeformatter(string name) {
  formatter f = null;
   try {
    class c = class.forname(name);
    f = (formatter)c.newinstance();
   } catch (exception e) {
    f = new simpleformatter();
   }
   return f;
  }

  // overridden abstract handler methods

  public void close() {
  }

  public void flush() {
 }

 /**
 * if record is loggable, format it and add it to window
 */
 public void publish(logrecord record) {
  string message = null;
  if (isloggable(record)) {
   try {
    message = getformatter().format(record);
   } catch (exception e) {
   reporterror(null, e, errormanager.format_failure);
   return;
  }
 try {
  window.addloginfo(message);
 } catch (exception e) {
  reporterror(null, e, errormanager.write_failure);
 }
}
}
}                            

  清单 6. loggingwindow 的定义

import java.awt.*;
import javax.swing.*;

public class loggingwindow extends jframe {
 private jtextarea textarea;
 
 public loggingwindow(string title, final int width,
 final int height) {
  super(title);
  eventqueue.invokelater(new runnable() {
   public void run() {
    setsize(width, height);
    textarea = new jtextarea();
    jscrollpane pane = new jscrollpane(textarea);
    textarea.seteditable(false);
    getcontentpane().add(pane);
    setvisible(true);
   }
  });
 }  

 public void addloginfo(final string data) {
  eventqueue.invokelater(new runnable() {
   public void run() {
    textarea.append(data);
   }
  });
 }
}

  执行 清单 3 中的 windowdump 程序将出现图 1 中的屏幕。因为没有从 logger 中删除控制台处理程序,所以堆栈溢出仍将出现在控制台上。

驯服tiger之线程中的默认异常处理(图一)
图 1. 记录的堆栈跟踪

  发生运行时异常时,可能要做许多工作来更改发生的问题。该代码的大部分都是 logging handler,但是,要执行更改,就必须细分 threadgroup ,重写 uncaughtexception() ,然后在该线程组中执行您的线程。不过,让我们通过只安装 thread.uncaughtexceptionhandler ,来看一看 tiger 的处理方式。

  使用 uncaughtexceptionhandler 的定制行为

  对于 tiger, thread 类定义中添加了一个新的公共内部类 uncaughtexceptionhandler ,更完整的名称为 thread.uncaughtexceptionhandler (其他类访问内部类时需要使用完整名称)。接口的定义是一个方法,如图 7 中所示:

  清单 7. uncaughtexceptionhandler 的定义

public interface thread.uncaughtexceptionhandler {
 public void uncaughtexception(thread, throwable);
}

  您可能没有注意到,清单 7 中的方法与我们前面重写的 threadgroup 的方法相同。实际上,现在由 threadgroup 类实现该接口。

  新的内部类可以帮助我们了解下列两对新方法,并有助于我们在 thread 中使用它们:

getuncaughtexceptionhandler() 和 setuncaughtexceptionhandler() 。
getdefaultuncaughtexceptionhandler() 和 setdefaultuncaughtexceptionhandler() 。

  第一对方法是 getuncaughtexceptionhandler() 和 setuncaughtexceptionhandler() ,它们允许您为当前线程及其后代定制行为,从而允许二十或更多的线程拥有自己的定制行为。不过,您更可能使用第二对方法 getdefaultuncaughtexceptionhandler() 和 setdefaultuncaughtexceptionhandler() 。如果使用第二对方法设置默认处理程序,那么没有自己的异常处理程序的所有线程都将使用默认处理程序。

  听起来好像很简单。为了进行说明,清单 8 转换了 清单 3 中的 threadgroup 友好的程序,使用新的 uncaughtexceptionhandler 接口:

清单 8. uncaughtexceptionhandler 示例

public class handlerdump {
 public static void main(string args[]) throws exception {
  thread.uncaughtexceptionhandler handler = new loggingthreadgroup("logger");
  thread.currentthread().setuncaughtexceptionhandler(handler);
  system.out.println(1 / 0);
 }
}

  该程序只是将 loggingthreadgroup 重用为 uncaughtexceptionhandler ,并没有创建新的处理程序实现。请注意,与原来的代码相比,新代码要简洁得多。

  其他线程更改

  thread 类不仅支持使用 tiger 添加的未捕获异常处理程序,它还支持使用 getallstacktraces() 获得所有有效线程的堆栈跟踪,或者支持使用 getstacktrace() 来只获得当前线程的堆栈跟踪。这两种堆栈跟踪都返回类型为 java.lang.stacktraceelement 的对象, java.lang.stacktraceelement 是 java 1.4 平台中添加的一个类,它可以让您生成自己的堆栈跟踪。同时,java 5 平台新添加的功能是一个惟一线程标识符(可以使用 getid() 获得该标识符)和一个新的 thread.state 类,以及与该类相关的 getthreadstate() 方法。最后一个线程更改是一个状态枚举表,该表是用来监视系统状态,而不是用来同步状态的。

  结束语

  像添加未捕获的异常处理程序这样的简单库更改,可以极大地增加原代码的可理解性。虽然在线程组级别上,新的库代码的功能与原来库代码的相同,但新模型中的易用性和灵活性远远超出了将代码调整为更新的方式所需的时间。当然,老方法仍然可以使用,但最好将代码更新为最新的库功能。

扫描关注微信公众号