identify duplicate calls within same call stack - java

Need some help regarding performance improvement in Java. Is there any way to understand whether there are any duplicate method calls(same method with same parameter values) within the same call stack.

To keep it more clear:

MethodA(int A) - returns int B.

Lets say that this method gets invoked from number of other classes and from other modules. In a single long chained transaction if this method gets called multiple times with same input parameters MethodA(1) it reduces the performance. Instead I believe that the better approach must be to use the result from first invocation every time instead of invoking MethodA(1) every time.

Is it is possible to identify the duplicate calls other than manually analyzing everything. For now I am trying to cache locally the results so avoiding the calls to the same method with same query parameter. But still trying to identify the duplicate calls so that can narrow it down to the root cause.

Any help would be highly appreciated.

1 answer

  • answered 2017-10-11 10:05 amitmah

    You have to be sure that given method has no side effects, as in every invocation with a given value of the parameter will always return the same value.

    You can use CGLIB to create method/class proxy and then use any cache implementation, return known or cached results for same input.

    Example (reference :

    List<String> proxyAry = (List<String>)Enhancer
    .create(TargetClass.class, new MyInvocationHandler(ary));
    static class MyInvocationHandler implements MethodInterceptor {
        private TargetClass<String> ary;
        public MyInvocationHandler(TargetClass<String> ary) {
            this.ary = ary;
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            if (isFouthGet(method, args)) {
                return "Bow!!";
            return proxy.invoke(ary, args);