Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does java differentiate Callable and Runnable in a Lambda?

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 );
    }
}
like image 298
curiouscupcake Avatar asked Aug 14 '18 19:08

curiouscupcake


People also ask

What is the difference between Callable and runnable in Java?

Callable interface and Runnable interface are used to encapsulate tasks supposed to be executed by another thread. However, Runnable instances can be run by Thread class as well as ExecutorService but Callable instances can only be executed via ExecutorService.

What is difference between run and call method in Java?

3) run() method does not return any value, its return type is void while the call method returns a value. The Callable interface is a generic parameterized interface and a Type of value is provided when an instance of Callable implementation is created.

What is difference between future and Callable interface in Java?

Future is used for storing a result received from a different thread, whereas Callable is the same as Runnable in that it encapsulates a task that is meant to be run on another thread.

How do I know if runnable is running?

Runnable runnable = ( ) -> { System. out. println( "Running the runnable at " + Instant. now() ); }; ScheduledExecutorService scheduledExecutorService = Executors.


2 Answers

The main difference in the signature is that a Callable returns a value while a Runnabledoes not. So this example in your code is a Callable, but definately not a Runnable, since it returns a value.

like image 191
Dorian Gray Avatar answered Oct 25 '22 04:10

Dorian Gray


See the documentation of ExecutorService which has 2 submit methods with one parameter:

  • submit(Callable<T> task) using Callable<T> which has method call() returning T.
  • submit(Runnable task) usnig Runnable which has method run() returning nothing (void).

Your lambda gives an output, returns something:

executorService.submit(() -> {
    System.out.println("Starting");
    int n = new Random().nextInt(4000);
    // try-catch-finally omitted
    return n;                                      // <-- HERE IT RETURNS N
});

So the lambda must be Callable<Integer> which is a shortcut for:

executorService.submit(new Callable<Integer>() {
    @Override
    public Integer call() throws Exception {
        System.out.println("Starting");
        int n = new Random().nextInt(4000);
        // try-catch-finally omitted
        return n;  
    }}
);

To compare, try the same with Runnable and you see it's method's return type is void.

executorService.submit(new Runnable() {
    @Override
    public void run() {
        // ...  
    }}
);
like image 30
Nikolas Charalambidis Avatar answered Oct 25 '22 04:10

Nikolas Charalambidis