Java Reference
In-Depth Information
Baz
!
null
The point here is that
java.lang.System.out.println()
has a return type of
void
(i.e., it does not return a value). However,
jjs
expects expressions to have a value
and, in the absence of a variable assignment, it will print it out. So the nonexistent
return value of
println()
is mapped to the JavaScript value
null
, and printed out.
Java programmers who are not familiar with JavaScript should
be aware that the handling of
null
and missing values in Java‐
Script is subtle, and in particular that
null != undefined
.
JavaScript functions and Java lambda expressions
The interoperability between JavaScript and Java goes to a very deep level. We can
even use JavaScript functions as anonymous implementations of Java interfaces (or
as lambda expressions). For example, let's use a JavaScript function as an instance of
the
Callable
interface (which represents a block of code to be called later). This has
only a single method,
call()
, which takes no parameters and returns
void
. In Nas‐
horn, we can use a JavaScript function as a lambda expression instead:
jjs
>
var
clz
=
Java
.
type
(
"java.util.concurrent.Callable"
);
jjs
>
print
(
clz
);
[
JavaClass
java
.
util
.
concurrent
.
Callable
]
jjs
>
var
obj
=
new
clz
(
function
()
{
print
(
"Foo"
);
}
);
jjs
>
obj
.
call
();
Foo
The basic fact that is being demonstrated is that, in Nashorn, there is no distinction
between a JavaScript function and a Java lambda expression. Just as we saw in Java,
the function is being automatically converted to an object of the appropriate type.
Let's look at how we might use a Java
ExecutorService
to execute some Nashorn
JavaScript on a Java thread pool:
jjs
>
var
juc
=
java
.
util
.
concurrent
;
jjs
>
var
exc
=
juc
.
Executors
.
newSingleThreadExecutor
();
jjs
>
var
clbl
=
new
juc
.
Callable
(
function
(){
\
java
.
lang
.
Thread
.
sleep
(
10000
);
return
1
;
});
jjs
>
var
fut
=
exc
.
submit
(
clbl
);
jjs
>
fut
.
isDone
();
false
jjs
>
fut
.
isDone
();
true
The reduction in boilerplate compared to the equivalent Java code (even with Java 8
lambdas) is quite staggering. However, there are some limitations caused by the
manner in which lambdas have been implemented. For example: