8043179: Lambda expression can mutate final field

Reviewed-by: vromero
This commit is contained in:
Archie L. Cobbs 2023-03-23 15:59:51 +00:00 committed by Vicente Romero
parent 147f3473d4
commit c00d0885ae
5 changed files with 35 additions and 0 deletions

View File

@ -2856,6 +2856,11 @@ public class Flow {
int nextadrPrev = nextadr;
ListBuffer<PendingExit> prevPending = pendingExits;
try {
// JLS 16.1.10: No rule allows V to be definitely unassigned before a lambda
// body. This is by design: a variable that was definitely unassigned before the
// lambda body may end up being assigned to later on, so we cannot conclude that
// the variable will be unassigned when the body is executed.
uninits.excludeFrom(firstadr);
returnadr = nextadr;
pendingExits = new ListBuffer<>();
for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {

View File

@ -0,0 +1,13 @@
/*
* @test /nodynamiccopyright/
* @summary Verify lambda expression can't mutate a final field
* @bug 8043179
* @compile/fail/ref=LambdaMutateFinalField.out -XDrawDiagnostics LambdaMutateFinalField.java
*/
class LambdaMutateFinalField {
final String x;
LambdaMutateFinalField() {
Runnable r1 = () -> x = "not ok";
this.x = "ok";
}
}

View File

@ -0,0 +1,2 @@
LambdaMutateFinalField.java:10:29: compiler.err.var.might.already.be.assigned: x
1 error

View File

@ -0,0 +1,13 @@
/*
* @test /nodynamiccopyright/
* @summary Verify lambda expression can't mutate a final variable
* @bug 8043179
* @compile/fail/ref=LambdaMutateFinalVar.out -XDrawDiagnostics LambdaMutateFinalVar.java
*/
class LambdaMutateFinalVar {
LambdaMutateFinalVar() {
final String x;
Runnable r1 = () -> x = "not ok";
x = "ok";
}
}

View File

@ -0,0 +1,2 @@
LambdaMutateFinalVar.java:10:29: compiler.err.var.might.already.be.assigned: x
1 error