我有一个对象调用 Counter 基本上看起来像这样:
private long count;
private long errors;
private long duration;
private long errorDuration;
有两个“时间”方法用于计时方法,它们返回一些东西和其他无效的方法。
public <T> T time(ReturningRunnable<T> runnable) {
long start = currentTimeMillis();
T result = null;
try {
result = runnable.run();
} catch (Throwable ex) {
errorDuration += currentTimeMillis() - start;
errors++;
throw runtime(ex);
}
duration += currentTimeMillis() - start;
count++;
return result;
}
public void time(Runnable runnable) {
time(new RunnableRunner(runnable));
}
我选择将异常重新抛出为运行时异常(因为我不喜欢检查异常),但您也可以让您的自定义 MyRunnable 接口抛出异常,然后捕获并重新抛出它们。这是上面的用法:
counter.time(new Runnable() {
@Override
public void run() {
// Do something
});
或者这个,在返回值的情况下:
return counter.time(new ReturningRunnable<Integer>() {
@Override
public Integer run() {
return 1; // You get the idea
});
我喜欢这个,因为我的计数器对象可以通过 JMX 公开并在我需要的地方注入。您可以通过反思来做您所要求的事情,但我认为那会很混乱(恕我直言)。