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

Glassfish.JEE6.使用拦截器测量性能,glassfish,java-ee-6,introspection,performancecounter,Glassfish,Java Ee 6,Introspection,Performancecounter,对于测量方法的执行时间,我看到了一些建议 public class PerformanceInterceptor { @AroundInvoke Object measureTime(InvocationContext ctx) throws Exception { long beforeTime = System.currentTimeMillis(); Object obj = null; try { obj = ctx.proceed();

对于测量方法的执行时间,我看到了一些建议

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课堂和a

countCalls++; 
对于measureTime()来说,它似乎也可以正常工作

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

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

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

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

private static final AtomicLong callCount = new AtomicLong();

private long getCallCount() {
   return callCount.get();
}

private void increaseCountCall() {
   callCount.getAndIncrement();
}