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

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -