Java

Profiling with Spring

Every application should have functional and non-functional tests. Non-functional include load and performance. So what happens when we do not meet the performance requirements? Obviously we try to figure out what is going on. This is called profiling. In this post I will write about how to profile an application with spring.

joao-silas-72563-unsplash

Profiling an application is a cross-cutting concern so it fits under the hood of aspect oriented programming. That means we need to define an aspect.

@Aspect
@Component
public class ProfileExecutionAspect {

    @Pointcut(value = "execution(public * *(..))")
    public void anyPublicMethod() {
    }

    @Around("anyPublicMethod() && @annotation(ProfileExecution)")
    public Object profileExecuteMethod(ProceedingJoinPoint jointPoint) throws Throwable {
        Signature signature = jointPoint.getSignature();
        String methodName = signature.toShortString();

        StopWatch stopWatch = new StopWatch(ProfileExecutionAspect.class.getName());
        stopWatch.start(methodName);

        Object result = jointPoint.proceed();

        stopWatch.stop();
        //log not sysout
        System.out.println(stopWatch.prettyPrint());
        return result;
    }
}

Here we have the point-cut annotated with @Pointcut. The execution of any public method which is annotated with @ProfileExecution. This way we can target any method. @Around is the most powerful type of advice, we have more control by using it.

The @ProfileExecution is just a simple annotation.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
@Documented
public @interface ProfileExecution {
}

That’s it. Just annotate your method with @ProfileExecution and check the logs. Simple enough.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.