Search code examples
javajava-8runnableexecutorserviceexecutor

"Runnable::run" - How is this creating an Executor instance?


I'm working on a project where the following line is used to create a test Executor member variable instance:

private Executor executor = Runnable::run;

The code runs and compiles but I don't understand how Runnable::run creates an instance of Executor since both are different interfaces.

Is anyone able to explain? In particular:

  • Where does the implementation of Runnable come from?
  • How is it assigned to an Executor implementation (since Executor is a different interface)?
  • What kind of Executor is created? e.g. single threaded or pooled
  • How would this be written before Java 8?

Thanks.


Solution

  • Executor is a @FunctionalInterface:

     public interface Executor {
         void execute(Runnable command);
     }
    

    You can re-write it like this to actually understand it better probably:

     Executor executor = (Runnable r) -> r.run(); // or Runnable::run