0

I would like to know how is it possible to measure the time of function execution in Java. Being more precise, I have a Class with a method getData(). This function is used to get the data from the external serivice and is used in multiuser application. I would like to monitor of time execution of this function by the MBeanServer. How to deal with it ? As far as I know, I have to create MBean and register it on the MBeanServer.

user109447
  • 1,069
  • 1
  • 10
  • 20

2 Answers2

0

If you don't want to view the time of execution constantly, a solution can be to log it.

Edit: A logger will write an information in a file and there an interesting fact for your case: the time of the log is written automatically. See tutorial on logger, and How do I time a method's execution in Java?

Community
  • 1
  • 1
  • glad to see your first answer, try and provide some useful code or direction instead of just a general line. Yes, a solution is to log it but that does not really fully answer the users question. – Benjamin Trent Jul 15 '14 at 15:38
0

There are two problems here. The first is how to measure how long the method takes. That's fairly straightforward. Something like this would work:

long start = System.nanoTime();
Object result = getData();
long elapsedTime = System.nanoTime() - start;

Now, what do you do with elapsedTime? I can think of two things. The first (and easiest) is to log it. This snippet assumes you're using a logging framework and have a reference to a logger appropriate for the current context:

logger.info("Method executed. elapsedTime=" + elapsedTime);

Unfortunately with this you won't be able to expose the data via an mbean. You've serialized the data, though, and can use something like Splunk or some custom script to parse these messages and present the data in a more visually pleasing form.

If you absolutely need to expose the data via an Mbean, you need to figure out how you're going to store the data. It could be in a List in your class where you just store execution times:

executionTracker.add(elapsedTime);

This is going to turn into a very large list very quickly, however. So you may need a custom class that manages the size of the list somehow. Once you have that data managed in a way that won't result in a memory leak, you can work on exposing the data via an MBean. But the bottom line is that exposing the data via an MBean means storing it and managing the storage of it, which is going to be complicated.

Another option is to use custom instrumentation packages that allow you to instrument specific method calls. I know New Relic offers this; there may be some open source options as well.

Community
  • 1
  • 1
Cameron
  • 1,868
  • 3
  • 21
  • 38