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

1

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.

Winger answered 6/10, 2017 at 13:24 Comment(1)
Method References.Merilynmeringue
S
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
Spaceport answered 6/10, 2017 at 13:34 Comment(4)
Thanks for replying. Where does the Runnable implementation come from? e.g. where is r instantiated?Winger
@Winger seems like you need to read a bit what lambda expression are and method references...Spaceport
@Winger executor is essentially a function. You give it a runnable to run. That's where the implementation comes from.Irritative
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.Winger

© 2022 - 2024 — McMap. All rights reserved.