0

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?

Supun Wijerathne
  • 11,964
  • 10
  • 61
  • 87

1 Answers1

1

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.

Supun Wijerathne
  • 11,964
  • 10
  • 61
  • 87
talex
  • 17,973
  • 3
  • 29
  • 66
  • @SupunWijerathne It is not changed so no need in synchronization. – talex Nov 23 '18 at 09:26
  • @SupunWijerathne They doesn't. Re-assignments are forbidden. That is why we have final or effectively-final constraint. – talex Nov 23 '18 at 10:08
  • @SupunWijerathne not before body, but inside and after. – talex Nov 23 '18 at 13:03
  • 1
    Yes. Compiler not smart enough to understand it. It is possible to loosen restriction, but it will make rules very complicated. – talex Nov 23 '18 at 13:32