I want to print the execution time for a method in java. Currently am using the following code,
long startTime = System.currentTimeMillis();
// method body
long runTime= System.currentTimeMillis() - startTime;
System.out.println(" XYZ Method execution time: " + runTime);
There are so many methods for which I would like to find the runtime in the project, is there any way to prevent writing this piece of code in every method?
The project uses Spring 2.5, Struts 2.
Edit:I do not want to add the logic to every method, I would like to, say, write the logic once and use some kind of configuration where I can specify the methods for which I need to print the execution time. So whenever the method is executed, automatically the run time should get printed to the console. One way is as said by me is to add the code to prologue and epilogue, but I do not want to edit the method as that would be time consuming and writing the same code wont be a good practice.
I recommend you take a look at the Metrics package from Codahale. This package collects various metrics (including timing) which is then reported via JMX or other mechanisms.
Why don't you just use a profiler, like YourKit or JVisualVM. JVisualVM comes with the JDK. If you really want to do this yourself, use java.lang.instrument and ASM to write your own agent. It's simple to add logic to the prologue and epilogue of a Java method using this approach.
Here's a link to get you started.
Option 1 :: Use AOP
Option 2 :: If you are logging at the right places (before & after), and are throwing in the time stamp in your logs, you could just use any analytics tools (logrythm, splunk's open source version, etc.) to just crunch your logs and figure out the times. However keep in mind logging is generally an expensive operation (well, so is AOP to some extent).
Whichever approach you take, make sure to count for the performance impact you are going to put on your application just to measure performance itself :-).
Take a look at the Spring AOP, you can use around advice to calculate method execution time
Spring 2.5
Spring 3.0 x
Related
I want to count how many times I make a HTTP GET when I use websockets and when I do not use websockets. I expect once when using websockets and n-times otherwise. I want to do this via JUnit, and I happen to be using Spring too. Are there any creative ways to count the times I make a GET with Jersey?
client.target(.....).get(....)
I don't know how to do this without cluttering my production code with test specific code.
If you code is defined using an interface, then I would use a Decorator pattern to add additional behavior. In this case additional behavior would be keeping track of the count of calls.
This approach is easy to configure if your concrete class is configured through Spring. Then in your Spring resource for the JUnit test, modify it to inject the Decorated class. There is no impact to existing production code.
If you add one static variable COUNT and increment it with every call - it will not hurt production at all. And you can use this variable not only for unit testing but even for production monitoring.
I've used both Play1.x and Play2.x, but I didn't find how Play distributes its request to different actions in its source code.
e.g.
http://HOST:9000/Application/index
Play could find the controller Application, and then invoke its index method.
I thought Play works this way:
Get URI's first part Application and init Application using reflection.
Get the second part of URI, index, invoke index() of Application using reflection.
But I don't know where's the code exactly.
And, If it using a lot of reflection, how could it handle millions of request ? I think reflection is a lot of slower than direct method call(Or Play make some magic optimize ?).
Route file get compiled into target/scala-2.10/src_managed/main/routes_routing.scala file.
Even if reflection would be involved why should it be slow? File need to be reflected once at app startup.
The route file points each uri to a specific method.
For example:
GET /clients/:id controllers.Clients.show(id: Long)
If you don't care about routes type-safety incorporated in Play 2.x you can easily write custom resolver which will catch all unhandled routes with Dynamic parts spanning several / so using simple string operations + reflections you can access any controller/action combination you want...
Anyway consider if your app's security is worth of this sacrifice.
PS.: hard believing that samples are not required to this approach, in other case let me know, I'll write something in free time
I just want to know if there is any API or any thing which tells me all the method name which have been executed during one execution of application.
For ex. Lets say I have application with 10000 methods and based on some condition different methods get executed. So during one execution lets say if 100 method getting executed then I would like to know name of all these 100 methods in order of their execution.
is it possible?
There are few options you can use to track your method calls.
1. JProfiler http://www.ej-technologies.com/products/jprofiler/overview.html
2. Your kit. http://www.yourkit.com/
3. In addition you can write an application that logs to file when enters to methods and exit using Aspects with Log4j or SL4j
I think there's probably a name for what I'm describing here, but I don't know it. So my first question would be to know the name of this technique.
Here's an example: suppose you're implementing live search on a web page. Everytime the user types in the search box, you fire a new search query, and the results are updated as often as possible.
This is a stupid thing to do because you'll send much more queries than you actually need. Sending a request once per 2-3 letters or at most once per 100 ms is probably sufficient.
A technique is thus to schedule the queries to be executed soon after a key is typed, and if there are still queries that were planned but not executed, cancel them since they're obsolete now.
Now more specifically, are there specific patterns or librairies for solving this problem in Java ?
I had to solve the problem in a Swing app, and I used an ExecutorService, which returned ScheduledFutures that I could cancel. The problem is that I had to manually create a Runnable for each method call I wanted to "buffer", and keep track of each Future to cancel it.
I'm sure I'm not the first person to implement something like this, so there must be a reusable solution somewhere ? Possibly something in Spring with annotations and proxies ?
Given the other answers, and after some searching, it seems there's indeed no library that does what I wanted.
I created one and put it on GitHub. Future readers of this question may find it interesting.
https://github.com/ThomasGirard/JDebounce
I don't think it's very good yet but at least it works and can be used declaratively:
#Debounce(delayMilliseconds = 100)
public void debouncedMethod(int callID, DebounceTest callback) { }
This is not solvable in Java without using some extra infrastructure like you did with executor and futures. It is not possible to solve this in syntactically concise manner in Java.
You will always need some sort of method result wrapper, because the mechanism returns immediately but the actual result is retrieved later. In your case this was accomplished via Future.
You will always need to be able to specify code to be executed in a manner that will allow delayed execution. In most languages this is accomplished using function pointers or function values or closures. In Java, lacking these language features, this is usually accomplished by passing an object that implements some sort of interface such as Runnable, Callable, that allows delayed execution of a block of code. There are other options but none of them are simple, such as using a dynamic proxy.
tl;dr
Can't do this in concise manner in Java.
What you need is called debouncing. You should check the jQuery Throttle/Debounce plugin (which is btw totally independent of jQuery except for using the same namespace). What you need is covered by the debounce part:
Using jQuery throttle / debounce, you can pass a delay and function to
$.debounce to get a new function, that when called repetitively,
executes the original function just once per “bunch” of calls,
effectively coalescing multiple sequential calls into a single
execution at either the beginning or end.
Underscore.js has the same method:
_.debounce(function, wait, [immediate])
Creates and returns a new debounced version of the passed function
which will postpone its execution until after wait milliseconds have
elapsed since the last time it was invoked. Useful for implementing
behavior that should only happen after the input has stopped arriving.
For example: rendering a preview of a Markdown comment, recalculating
a layout after the window has stopped being resized, and so on.
// example: debounce layout calculation on window resize
var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);
[Edit]
I mistakenly read "Javascript" instead of Java. Actual Java solution was written by OP afterwards.
Suppose I have a class called Foo. This class will be modified by many people, and WILL print information to the console. To this effect, we have the following method:
private void print(String message){ ... }
which prints out to the screen in the format we want.
However, while reviewing code from other devs I see that they constantly call System.out.println(...)
instead, which results in barely-readable printouts.
My question is the following: is it possible to prevent any and every use of System.out.println() in Foo.java? If so, how?
I've tried looking this up, but all I found had to do with inheritance, which is not related to my question.
Thanks a lot!
N.S.
EDIT: I know that whatever I have to do to prevent the use of a method could be removed by a dev, but we have as a policy never to remove code marked //IMPORTANT so it could still be used as a deterrent.
EDIT2: I know I can simply tell the devs not to do it or use code reviews to filter the "errors" out but 1) I'm already doing it and it costs a lot of time and 2) the question is whether this is possible or not, NOT how to deal with my devs.
public methods are just that - public. There is no way to restrict access to them.
This kind of problem is usually "solved" by setting up some code-checker like PMD or checkstyle and integrating them into the continuous integration build. So violations of these stuff will be emailed to someone with a big hammer :-)
Although communicating that developers should not use System.out directly would be preferred, you could set System.out to another PrintStream, then use the alternative PrintStream in the private method. That way, when people use System.out.println they won't output anything but you'll still be able to use the alternative PrintStream... something like they do here: http://halyph.blogspot.com/2011/07/how-to-disable-systemout.html
Pre-commit hooks for your revision control system (SVN, Git, Mercurial) can grep for uses of System.{err,out} and prevent commit if they occur.
http://stuporglue.org/svn-pre-commit-hook-which-can-syntax-check-all-files/ is an example that takes an action for different changed files based on file extension for SVN. You should be able to modify that example to take an example based on some subset of Java files and reject if something like the following is true
egrep -q '\bSystem\.(err|out)\b'
You can redirect System.out calls to a streams that ignores the output or that redirects it to your logging system.
System.setOut(printStream);
You can also kill those using System.out.println in a production environment.
You can replace the OutputStream of System with your own implementation that would either throw an exception, or redirect the call to your own print implementation (which you would need to make public).
No, it's not possible to 100% prevent a class from ever using a specific method in Java.
Having that said...
My suggestion would be to add code analysis to your build process and failing the build on any occurrence of System.out.println. A good place to start if you're interested in going this route would be to check out PMD.
Also... have some constructive discussions with your developers and talk about why they're doing what they're doing. Good luck.