Profiling a Java Spring application
I've done this using Spring AOP.
Sometime I need an information about how much time does it take to execute some methods in my project (Controller's method in example).
In servlet xml I put
<aop:aspectj-autoproxy/>
Also, I need to create the class for aspects:
@Component
@Aspect
public class SystemArchitecture {
@Pointcut("execution(* org.mywebapp.controller..*.*(..))")
public void businessController() {
}
}
And profiler aspect:
@Component
@Aspect
public class TimeExecutionProfiler {
private static final Logger logger = LoggerFactory.getLogger(TimeExecutionProfiler.class);
@Around("org.mywebapp.util.aspects.SystemArchitecture.businessController()")
public Object profile(ProceedingJoinPoint pjp) throws Throwable {
long start = System.currentTimeMillis();
logger.info("ServicesProfiler.profile(): Going to call the method: {}", pjp.getSignature().getName());
Object output = pjp.proceed();
logger.info("ServicesProfiler.profile(): Method execution completed.");
long elapsedTime = System.currentTimeMillis() - start;
logger.info("ServicesProfiler.profile(): Method execution time: " + elapsedTime + " milliseconds.");
return output;
}
@After("org.mywebapp.util.aspects.SystemArchitecture.businessController()")
public void profileMemory() {
logger.info("JVM memory in use = {}", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
}
}
That's all. When I request a page from my webapp, the information about method executing time and JVM memory usage prints out in my webapp's log file.
You can use an open source java profiler such as Profiler4J:
http://profiler4j.sourceforge.net/
or Netbeans comes with a built in profiler and Eclipse also has profiling capabilities, however I found Profiler4J easier to use since it has a nice graph showing you the most time consuming methods.
This works well in STS (eclipse), just follow the instructions on the site.
Here's a general discussion with recommended tools & techniques.
Basically, it is entirely natural to assume if you want to find out how to make an app faster, that you should start by measuring how long functions take. That's a top-down approach.
There's a bottom-up approach that when you think about it is just as natural. That is not to ask about time, but to ask what it is doing, predominantly, and why it is doing it.
I recommend VisualVM for general application profiling. It is available in the JDK from version 1.6_10, and imho much faster and usable than Eclipse TPTP.
(If your Spring application works in an application server (e.g. Tomcat) you could try to deploy it to the tc Server developer edition (available in the STS downloads). It has interesting monitoring capabilities. It seems that tc Server developer edition is not maintained anymore.)
UPDATE 2019.02.22.: updated VisualVM url (thanks for @Jeff) and tc Server information. Personally I currently use Glowroot for monitoring Spring applications running in an application server.