The reason for a local variable to be final or effectively final this because of concurrency issues. In the jls 8 specification, it states the following.
The restriction to effectively final variables prohibits access to dynamically-changing local variables, whose capture would likely introduce concurrency problems.
All good and sweet, but I did a little experiment. What if I synchronize the method, that would eliminate the possibility of dynamically-changing local variable because I am guaranteed only a single thread can execute this code. But the compile threw an error saying it has to be final or effectively final.
Is logic right?
Consider the following code:
public synchronized void capture() {
int localVariable = 100;
Interf i = (text) -> System.out.println(text + localVariable);
i.m1("This local variable is: ");
localVariable = 1000;
}
}
SwingUtils.invokeLater(() -> System.out.println(localVariable)). What should this print?