Skip to content

Commit c00d088

Browse files
archiecobbsVicente Romero
authored andcommitted
8043179: Lambda expression can mutate final field
Reviewed-by: vromero
1 parent 147f347 commit c00d088

File tree

5 files changed

+35
-0
lines changed

5 files changed

+35
-0
lines changed

src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2856,6 +2856,11 @@ public void visitLambda(JCLambda tree) {
28562856
int nextadrPrev = nextadr;
28572857
ListBuffer<PendingExit> prevPending = pendingExits;
28582858
try {
2859+
// JLS 16.1.10: No rule allows V to be definitely unassigned before a lambda
2860+
// body. This is by design: a variable that was definitely unassigned before the
2861+
// lambda body may end up being assigned to later on, so we cannot conclude that
2862+
// the variable will be unassigned when the body is executed.
2863+
uninits.excludeFrom(firstadr);
28592864
returnadr = nextadr;
28602865
pendingExits = new ListBuffer<>();
28612866
for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/*
2+
* @test /nodynamiccopyright/
3+
* @summary Verify lambda expression can't mutate a final field
4+
* @bug 8043179
5+
* @compile/fail/ref=LambdaMutateFinalField.out -XDrawDiagnostics LambdaMutateFinalField.java
6+
*/
7+
class LambdaMutateFinalField {
8+
final String x;
9+
LambdaMutateFinalField() {
10+
Runnable r1 = () -> x = "not ok";
11+
this.x = "ok";
12+
}
13+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
LambdaMutateFinalField.java:10:29: compiler.err.var.might.already.be.assigned: x
2+
1 error
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/*
2+
* @test /nodynamiccopyright/
3+
* @summary Verify lambda expression can't mutate a final variable
4+
* @bug 8043179
5+
* @compile/fail/ref=LambdaMutateFinalVar.out -XDrawDiagnostics LambdaMutateFinalVar.java
6+
*/
7+
class LambdaMutateFinalVar {
8+
LambdaMutateFinalVar() {
9+
final String x;
10+
Runnable r1 = () -> x = "not ok";
11+
x = "ok";
12+
}
13+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
LambdaMutateFinalVar.java:10:29: compiler.err.var.might.already.be.assigned: x
2+
1 error

0 commit comments

Comments
 (0)