2

ExecutorService has two overloaded methods

  1. ExecutorService.submit(Callable)
  2. ExecutorService.submit(Runnable)

Instance of which class Runnable or Callable is created when I write the below code.

executor.submit(()->System.out.println("Running in : " + Thread.currentThread().getName()));

If this is an instance of Runnable, how do I pass an instance of Callable or vice-versa to ExecutorService while using lambda expression?

  • 1
    You have to return a value, instead of printing your string you should return it, and print the result from the thread that calls future.get. – matt Aug 10 '16 at 16:46
  • Another way to distinguish which method you use is to caste. http://ideone.com/LXmdsq – matt Aug 10 '16 at 17:16

2 Answers2

4

Since your lambda does not return a value, which is what Callable.call() requires, it's a Runnable.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • Is there any way to prove this programmatically? – Tejas Unnikrishnan Aug 10 '16 at 16:42
  • 3
    I think the compiler proves it really well, since it won't compile incorrect code. Try to create a `Runnable` that returns a value or a `Callable` that doesn't return a value. – Kayaman Aug 10 '16 at 16:45
  • Is this question really a duplicate? The associated link did not answer my query regarding `Runnable` and `Callable` – Tejas Unnikrishnan Aug 10 '16 at 16:54
  • Don't ask me, I didn't close this. But it does seem to be extremely related to your question. Meaning that there's no problem with lambda ambiguity when there's a return value vs. a void method. – Kayaman Aug 10 '16 at 16:54
  • 2
    @TejasUnnikrishnan it addresses the answer for your question, you need to return a value. You distinguish which method you are going to use by returning a value. eg. Runnable does not return a value, and Callable returns a value. So `submit(()->"stat")` uses `call`, and `submit(()->System.out.println("stat"));` uses `run`. The other question addresses a bug, where the compiler did know how you specify which method you are overriding. I don't think they're duplicate questions. – matt Aug 10 '16 at 17:05
1

To have a Callable lambda you have to return something.

executor.submit(() -> {great_calculation(); return calculated_value;});
Jean Jung
  • 1,200
  • 12
  • 29