Search code examples
javalambdaconcurrencyjava-8final

How JRE can create concurrency problems for lambda bodies with non effectively final local variables?


I'm referring to this common compile error we often get with lambdas.

Variable used in lambda expression should be final or effectively final

which warns us not to use non definite assignments inside lambda body. I understand what it says.

In JLS, it clearly says

The restriction to effectively final variables prohibits access to dynamically-changing local variables, whose capture would likely introduce concurrency problems.

But I don't have a very good idea how it can create problems.

Can some one please explain me any scenario (preferably with an example) how it can create potential concurrency issues, when we try to violate this?


Solution

  • If you capture a variable into a lambda expression and pass it to another thread, then access to this variable is not synchronized. This leads to concurrency problems.