Search code examples
javajava-8functional-interface

Functional Interfaces in Java 8 (Method execution time logger)


I have two methods:

class C1
{

  void m1() {//does sth}

  void m2(int x1, int x2) {//does sth}

 }

//Log the time taken by any method

 logMethodExecTime(m1);
 logMethodExecTime(m2);

Not sure how can I use JDK8 functional interfaces and method references to define the right syntax for method 'logMethodExecTime' ?

Following is not working:

class Utils
{
   public static void logMethodExecTime(Supplier<Void> s)
   {
     long start = System.nanoTime();
     s.get();
     long end = System.nanoTime();
     System.out.println(((end-start)/1000000000d) + " secs");
   }
 }

and invocation:

      C1 c = new C1();  
      Utils.logMethodExecTime(c::m1);

//Also how can we have one single definition of 'logMethodExecTime' 
//to accept any method with any number of args    
      Utils.logMethodExecTime(c::m2);

Solution

  • Instead of Supplier<Void> you should use a plain Runnable, and instead of insisting on method references you'll need an explicit lambda which contains the method invocation, capturing any arguments it needs. For example:

    logMethodExecTime(() -> m2(17, 37));
    

    Note that the lambda is not necessarily just a single method invocation. This gives you more flexibility in what you can measure.