9

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.

T.R.
  • 171
  • 8

1 Answers1

6

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
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • Thanks for replying. Where does the Runnable implementation come from? e.g. where is r instantiated? – T.R. Oct 06 '17 at 13:37
  • @T.R. seems like you need to read a bit what lambda expression are and method references... – Eugene Oct 06 '17 at 13:43
  • 2
    @T.R. `executor` is essentially a function. You give it a runnable to run. That's where the implementation comes from. – Carcigenicate Oct 06 '17 at 13:45
  • Thanks guys. I think I understand now. It was the threading aspect that was confusing me - since `Executor` can be used to control threading - but I think I understand now that all `runnables` passed to this particular executor will run in the same thread. – T.R. Oct 06 '17 at 14:00