I got this little code to test out Callable
. However, I find it pretty confusing how the Compiler could know if the Lambda is for the Interface Callable or Runnable since both don't have any parameter in their function.
IntelliJ, however, shows that the Lambda employs the code for a Callable.
public class App {
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.submit(() ->{
System.out.println("Starting");
int n = new Random().nextInt(4000);
try {
Thread.sleep(n);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
System.out.println("Finished");
}
return n;
});
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES );
}
}
The main difference in the signature is that a
Callable
returns a value while aRunnable
does not. So this example in your code is aCallable
, but definately not aRunnable
, since it returns a value.See the documentation of ExecutorService which has 2
submit
methods with one parameter:submit(Callable<T> task)
usingCallable<T>
which has methodcall()
returningT
.submit(Runnable task)
usnigRunnable
which has methodrun()
returning nothing (void
).Your lambda gives an output, returns something:
So the lambda must be
Callable<Integer>
which is a shortcut for:To compare, try the same with
Runnable
and you see it's method's return type isvoid
.