Mutation of "free variables" lambda expressions

I am reading this fantastic article on lambda expressions, and the following is not cleared of me:

  • Does the Lambda expression invoke the value of free variables or refernse / pointer for each of them? (I think the answer is the last, because if not, the mutation of the free variables will be valid).

Do not expect the compiler to catch all concurrent access errors. the ban on mutation takes place only for local variables.

I'm not sure that the experiment itself will cover all cases, so I'm looking for clearly defined rules:

  1. What free varibles can be mutated inside a Lambda expression (static / properties / local variables / parameters) and which can be mutated from the side when used inside a Lambda expression?
  2. Can I mutate every free variable after the end of the block of the Lambda expression after I used it (read or named one of its methods) without displaying the Lambda expression?

Do not expect the compiler to catch all concurrent access errors. the ban on mutation takes place only for local variables. If matchis is an instance or static variable of the enclosing class, then no error is reported, although the result is undefined.

  1. Is the result of the mutation undefined even if I use the synchronization algorithm?

Update 1:

- , .

, - , ?

+4
2

"" . , .

, :

 int x = 3;

 Runnable r = () -> {
    x = 6; // Local variable x defined in an enclosing scope must be final or effectively final
 };

( ):

    final int x[] = { 0 };

    Runnable r = () -> {
        x[0] = 6;
    };

, , matches:

 List<Path> matches = new ArrayList<>();
    List<Path> files = List.of();
    for (Path p : files) {
        new Thread(() -> {
            if (1 == 1) {
                matches.add(p);
            }
        }).start();
    }

. ( matches - effectively final); undefined results. side-effects . undefined , matches thread-safe.

: Does the result of the mutation is undefined even when I use a synchroniziton algorithm?. . outside lambda ( ) - , , .

, - , - .

1) : - - , free-variables , . , . , . , , final or effectively final, . - , ; ( - ). 3) - .

+6

" " . ( ), .

, static . ( ) this. , , , . static.

, final, . , - , . , , -. , , - concurrency, .

ArrayList<String> list=new ArrayList<>(Arrays.asList("foo", "bar"));
list.removeIf(s -> list.remove("bar"));

java.util.ConcurrentModificationException - .

, , , - . API, .

, , , Stream, . , , , , . , .

3 " ", , , - ( ).

, , . , .

+6

Source: https://habr.com/ru/post/1676649/


All Articles