Glassfish-JEE6-使用拦截器测量性能



为了测量方法的执行时间,我看到了使用的建议

public class PerformanceInterceptor {
   @AroundInvoke
   Object measureTime(InvocationContext ctx) throws Exception {
   long beforeTime = System.currentTimeMillis();
   Object obj = null;
   try {
      obj = ctx.proceed();
      return obj;
   }
   finally {
      time = System.currentTimeMillis() - beforeTime;
      // Log time
   }
}

然后放入

@Interceptors(PerformanceInterceptor.class) 

在你想要测量的任何方法之前。

不管怎样,我试过了,看起来效果很好。

我还添加了

public static long countCalls = 0;

到PerformanceInterceptor类和

countCalls++; 

到measureTime(),它似乎也正常工作。

戴上我的新手帽,我会问我对countCalls的使用是否正常,即Glassfish/JEE6对我在Java类中使用静态变量很好用作拦截器。。。。特别是在螺纹安全方面。我知道通常,您应该在Java中同步类变量的设置,但我不知道JEE6/Glassfish的情况如何。有什么想法吗?

在这种情况下,容器没有提供任何额外的线程安全性。每个bean实例都有自己的拦截器实例。因此,多个线程可以同时访问静态countCalls。

这就是为什么你必须像往常一样保护它的读写。其他可能性是使用AtomicLong:

private static final AtomicLong callCount = new AtomicLong();
private long getCallCount() {
   return callCount.get();
}
private void increaseCountCall() {
   callCount.getAndIncrement();
}

正如预期的那样,这些解决方案只有在所有实例都在同一JVM中时才能工作,因为需要集群共享存储。

最新更新