I wanted to know if this is an implementation detail...
In Java, used local variables are captured for anonymous classes, and lambdas. For anonymous classes, the this
is also captured in a non static context whether needed or not.
It appears, however, any local variable referenced is captured even if not used for Oracle JDK 8 update 181.
public static void main(String[] args) {
Thread t = Thread.currentThread();
Runnable run = new Runnable() {
@Override
public void run() {
t.yield();
}
};
Runnable run2 = () -> t.yield();
run.run();
run2.run();
}
the byte code for the anonymous Runnable
is
// access flags 0x1
public run()V
L0
LINENUMBER 8 L0
ALOAD 0
GETFIELD UnusedLocalVariable$1.val$t : Ljava/lang/Thread;
POP
INVOKESTATIC java/lang/Thread.yield ()V
L1
LINENUMBER 9 L1
RETURN
L2
LOCALVARIABLE this LUnusedLocalVariable$1; L0 L2 0
MAXSTACK = 1
MAXLOCALS = 1
As you can see, it captures the local variable which it loads, but always discards at runtime.
The lambda does much the same, also capturing the variable.
Is this always the case, or an implementation detail?