Just found a strange and interesting Lambda behavior.
Let's have the following class:
private class Task implements Runnable {
@Override
public void run() {
// something to process
}
}
The following statement is compiling and running:
Callable task = Task::new;
Could somebody explain why this is possible ?
EDIT:
Based on answers below, check the following statements:
1.
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(Task::new);
2.
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(new Task());
On the first glance, seems the same, but actually does a totally different thing.
What happens here is exactly the above situation.
The reason is that ExecutorService has two methods:
submit(Runnable);
submit(Callable);
So, using the code from 1. the executor will process the following on it's internal thread:
new Task()
The version from 2. will actually call the submit(Runnable) method and the code from Task.run will be executed.
Conclusion: just be careful with Lambdas :)