Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 253
NitinS Avatar asked May 01 '26 04:05

NitinS


1 Answers

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.

like image 140
Marko Topolnik Avatar answered May 02 '26 18:05

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!