java - Lambda: Callable variable initiated with a Runnable instance -


just found strange , interesting lambda behavior.

let's have following class:

private class task implements runnable {     @override     public void run() {        // process     } } 

the following statement compiling , running:

callable task = task::new; 

could explain why possible ?

edit:

based on answers below, check following statements:

1.

executorservice executor = executors.newsinglethreadexecutor(); executor.submit(task::new);

2.

executorservice executor = executors.newsinglethreadexecutor(); executor.submit(new task());

on first glance, seems same, totally different thing.

what happens here above situation.

the reason executorservice has 2 methods:

submit(runnable); submit(callable);

so, using code 1. executor process following on it's internal thread:

new task()

the version 2. call submit(runnable) method , code task.run executed.

conclusion: careful lambdas :)

the callable not initialized runnable instance, initialized method reference task constructor produce runnable when executed.

in other words, if execute callable, return new task object has not yet been run. task implements runnable irrelevant here.

this clearer if didn't use raw type. task::new can assigned callable<task> because takes no parameters , returns task.


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -