Java Lambda Expression with Non-final Function Paramter

后端 未结 2 826
日久生厌
日久生厌 2020-12-22 00:46

I am trying to simply time a function by using the Runnable interface to wrap around whichever function I need.

private static double time(Runnable runnable)         


        
相关标签:
2条回答
  • 2020-12-22 01:27

    You can simply copy the variable value to separate final variable like this:

    double timer = 0;
    int size = 0;
    while(true) {
      final finalSize = size;
      timer = time(() -> functionB(finalSize));
      size *= 10;
    }
    

    Also, I can advice you to make some more timing functions for various amount of parameters for functions you want to time. Here how you can do it:

    public class Test {
    
        public static void main(final String[] args) {
            int ttt = 0;
            time(ttt, Test::func);
            time(ttt, ttt, Test::func);
        }
    
        public static void func(int i) {
    
        }
    
        public static void func(int i, int j) {
    
        }
    
        public static <T> double time(T arg, Consumer<T> func) {
            long startTime = System.nanoTime();
            func.accept(arg);
            return (System.nanoTime() - startTime) / 1000000000.0;
        }
    
        public static <T1, T2> double time(T1 arg1, T2 arg2, BiConsumer<T1, T2> func) {
            long startTime = System.nanoTime();
            func.accept(arg1, arg2);
            return (System.nanoTime() - startTime) / 1000000000.0;
        }
    
    }
    
    0 讨论(0)
  • 2020-12-22 01:45

    Try this.

    public static void main(String[] args) {
        double timer = 0;
        final int[] size = {1};
    
        while(timer <= 10) {
            timer = time(() -> functionB(size[0]));
            size[0] *= 10;
        }
    }
    

    Lambda expression refers to the free variables by copying them inside. So the free varibles must not be changed (must be final). But when you pass size[0], lambda expression copies array variable size. It is final.

    0 讨论(0)
提交回复
热议问题