I was wondering recently as Runnable is very often used in a functional context. At the same time according to javadoc its semantical meaning is very close to multithreading while it is not aways used in such context:
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run. This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped.
Is Runnable
equivalent to Supplier<Void>
? Or is Runnable
equivalent to Function<Void,Void>
and why is it not Supplier then ? How does Runnable align to the java.util.function package already presented functional interfaces.
Runnable
is it. There was an intentional choice (see Brian Goetz here) not to add a functional interface to the java.util.function
package that is effectively equivalent to Runnable
. One of the major ideas behind Java's implementation of lambdas (the idea that all uses of it must be where some functional interface is required, and that the lambda then becomes an implementation of that functional interface) is intended to ensure that Java post-lambda is more or less compatible with APIs designed pre-lambda, without any real need to release an incompatible 'v2' edition with a more Java8+ style API for the majority of existing APIs out there.
Introducing a variant of Runnable
solely for it to exist in the java.util.function
package would run counter to that idea.
Note that Runnable
and Supplier<Void>
and Function<Void, Void>
might feel very similar but are utterly incompatible in javaland. Void
isn't special; it's just a type, same as any other. For example, if you are making a Supplier<Void>
lambda, you need to actually return something, and you can only return null
; there is no non-hacky way to make instances of the Void
type. Whereas for void
, you don't have to (and can't).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With