Mutating instance or local object variables in Lambda java 8
java, java-8, lambda
Solution
In general: yes, you may get concurrency problems, but only the ones you already had. Lambdafying it won't make code non-threadsafe where it was before, or vice versa. In the example you give, your code is (probably) threadsafe because an `ActionListener` is only ever called on the event-dispatching thread. Provided you have observed the Swing single-threaded rule, no other thread ever accesses `jLabel`, and if so there can be no thread interference on it. But that question is orthogonal to the use of lambdas.
Problem
I know that for concurrency reasons I cannot update the value of a local variable in a lambda in Java 8. So this is illegal: ``` double d = 0; orders.forEach( (o) -> { d+= o.getTotal(); }); ``` But, what about updating an instance variable or changing the state of a local object?, For example a Swing application I have a button and a label declared as instance variables, when I click the button I want to hide the label ``` jButton1.addActionListener(( e) -> { jLabel.setVisible(false); }); ``` I get no compiler errors and works fine, but... is it right to change state of an object in a lambda?, Will I have concurrency problems or something bad in the future? Here another example. Imagine that the following code is in the method doGet of a servlet Will I have some problem here?, If the answer is yes: Why? ``` String key = request.getParameter("key"); Map<String, String> resultMap = new HashMap<>(); Map<String, String> map = new HashMap<>(); //Load map map.forEach((k, v) -> { if (k.equals(key)) { resultMap.put(k, v); } }); response.getWriter().print(resultMap); ``` What I want to know is: When is it right to mutate the state of an object instance in a lambda?