Are Java 8 lambdas compiled as inner classes, methods or something else? -
this question has answer here:
- how java lambda functions compiled? 1 answer
i have read article today regarding lambdas:
http://www.infoq.com/articles/java-8-lambdas-a-peek-under-the-hood
the article suggests, lambdas are not implemented anon inner classes (due performance). gives example lambda expression can compiled (static) method of class.
i have tried simple snippet:
private void run() { system.out.println(this); givehello(system.out::println); } private void givehello(consumer<string> consumer) { system.out.println(consumer); consumer.accept("hello"); }
and output :
sample.main@14ae5a5 sample.main$$lambda$1/168423058@4a574795 hello
so it's not same instance. it's not central "lambda factory" instance either..
how lambdas implemented then?
the expression itself, assuming pass actual lambda expression , not method reference, compiled separate, synthetic method. in addition formal arguments expected functional interface (e.g., single string
in case of consumer<string>
), include arguments captured values.
at code location lambda expression or method reference appears, invokedynamic
instruction emitted. first time instruction hit, call made bootstrap method on lambdametafactory
. bootstrap method fix actual implementation of target functional interface delegates target method, , gets returned. target method either synthetic method representing lambda body or whichever named method provided using ::
operator. while class implements functional interface is being created, process deferred; not happen @ compile time.
finally, runtime patches invokedynamic
site bootstrap result1, constructor call generated delegate captured values passed in, including (possibly) invocation target2. alleviates performance hit removing bootstrapping process subsequent calls.
1 see java.lang.invoke end of chapter "timing of linkage", courtesy of @holger.
2 in case of lambda no captures, invokedynamic
instruction resolve shared delegate instance can reused during subsequent calls, though implementation detail.
Comments
Post a Comment